huang
2025-10-22 3eaf0f2f1b909ac429cac9fc26af767ddecda065
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.mes.tools;
 
import liquibase.pro.packaged.C;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * @author huang
 * @since 2025/10/22
 */
@Configuration
public class WebSocketExecutorConfig {
    @Bean("webSocketSenderPool")
    public ExecutorService webSocketSenderPool() {
        return new ThreadPoolExecutor(
                2, // 核心线程数:根据客户端数量设置(一般2-5足够)
                4, // 最大线程数:客户端峰值时临时扩容
                30L, TimeUnit.SECONDS,
                new SynchronousQueue<>(), // 同步队列:无缓冲,直接提交给线程执行
                new ThreadFactory() {
                    private final AtomicInteger count = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r, "ws-sender-thread-" + count.getAndIncrement());
                        thread.setDaemon(true); // 守护线程:应用退出时自动销毁
                        return thread;
                    }
                },
                new ThreadPoolExecutor.DiscardOldestPolicy() // 队列满时:丢弃最旧的任务,执行新任务(避免消息堆积过久)
        );
    }
}