com.yanyun.log.websocket.LogSocketConfig Maven / Gradle / Ivy
package com.yanyun.log.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
public class LogSocketConfig implements WebSocketMessageBrokerConfigurer {
//业务连接池
private ExecutorService senderThreadPool;
public LogSocketConfig(ExecutorService senderThreadPool) {
this.senderThreadPool = senderThreadPool;
}
//注册连接socket端点地址
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/log/monitor")
.setAllowedOrigins("*") //设置跨域
.withSockJS();
}
//设置定时任务,将线程池信息刷给前端websocket中
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
@Scheduled(fixedRate = 5000)
public void scheduleJob() {
Map map = new HashMap();
map.put("sender", getPoolInfo(senderThreadPool));
simpMessagingTemplate.convertAndSend("/log/audio", map);
}
private Map getPoolInfo(ExecutorService pool) {
Map map = new HashMap();
ThreadPoolExecutor executor = (ThreadPoolExecutor) pool;
map.put("taskCount", executor.getTaskCount());//线程池的总任务,包括已经完成的
map.put("completedTaskCount", executor.getCompletedTaskCount());//已经执行完成的任务
map.put("largestPoolSize", executor.getLargestPoolSize());//曾创建过的最大线程数量
map.put("poolSize", executor.getPoolSize());//线程池线程数
map.put("queueSize",executor.getQueue().size());//当前排队线程数
map.put("activeCount", executor.getActiveCount());//活跃的线程数
return map;
}
}