|
|
|
@ -1,7 +1,11 @@ |
|
|
|
package com.gaotao.config; |
|
|
|
|
|
|
|
import org.springframework.context.annotation.Bean; |
|
|
|
import org.springframework.context.annotation.Configuration; |
|
|
|
import org.springframework.messaging.simp.config.MessageBrokerRegistry; |
|
|
|
import org.springframework.messaging.simp.config.SimpleBrokerRegistration; |
|
|
|
import org.springframework.scheduling.TaskScheduler; |
|
|
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; |
|
|
|
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; |
|
|
|
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; |
|
|
|
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; |
|
|
|
@ -42,7 +46,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { |
|
|
|
// 启用简单消息代理,用于向客户端推送消息 |
|
|
|
// /topic - 公共广播(一对多) |
|
|
|
// /queue - 点对点(一对一) |
|
|
|
config.enableSimpleBroker("/topic", "/queue"); |
|
|
|
SimpleBrokerRegistration simpleBroker = config.enableSimpleBroker("/topic", "/queue"); |
|
|
|
// 开启心跳并绑定调度器,避免长时间断网后连接假死无法及时回收。 |
|
|
|
simpleBroker.setHeartbeatValue(new long[]{10000, 10000}); |
|
|
|
simpleBroker.setTaskScheduler(dashboardWebSocketTaskScheduler()); |
|
|
|
|
|
|
|
// 客户端发送消息的目的地前缀 |
|
|
|
config.setApplicationDestinationPrefixes("/app"); |
|
|
|
@ -62,7 +69,23 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { |
|
|
|
// 前端通过此端点建立WebSocket连接 |
|
|
|
registry.addEndpoint("/ws/dashboard") |
|
|
|
.setAllowedOriginPatterns("*") // 允许所有跨域访问 |
|
|
|
.withSockJS(); // 启用SockJS降级支持(当浏览器不支持WebSocket时) |
|
|
|
.withSockJS() |
|
|
|
// 加快异常断线会话的清理,避免长期网络抖动后积压无效会话。 |
|
|
|
.setHeartbeatTime(10000) |
|
|
|
.setDisconnectDelay(30000); // 启用SockJS降级支持(当浏览器不支持WebSocket时) |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 提供WebSocket心跳调度器 |
|
|
|
*/ |
|
|
|
@Bean("dashboardWebSocketTaskScheduler") |
|
|
|
public TaskScheduler dashboardWebSocketTaskScheduler() { |
|
|
|
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); |
|
|
|
taskScheduler.setPoolSize(1); |
|
|
|
taskScheduler.setThreadNamePrefix("ws-heartbeat-"); |
|
|
|
taskScheduler.setRemoveOnCancelPolicy(true); |
|
|
|
taskScheduler.initialize(); |
|
|
|
return taskScheduler; |
|
|
|
} |
|
|
|
} |
|
|
|
|