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() // 队列满时:丢弃最旧的任务,执行新任务(避免消息堆积过久)
|
);
|
}
|
}
|