解决SpringBoot连接Websocket报:请求路径 404 No static resource websocket.
@EnableWebSocketMessageBroker
@Configurable
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket") // 注册端点
.addInterceptors(handshakeInterceptor()) // 拦截器
.setAllowedOrigins("*") // 跨域配置
.withSockJS() // 启动wockjs支持
.setHeartbeatTime(5000) // 设置心跳时间 5s
;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//指定了消息代理的目标前缀,即服务器会将以“/screen/user”大屏用户
registry.enableSimpleBroker("/app");
}
@Override
public void configureWebSocketTransport(final WebSocketTransportRegistration registry) {
registry.setSendTimeLimit(15 * 1000); // 发送消息的最大时间限制
registry.setMessageSizeLimit(128 * 1024); // 设置文本消息的大小限制
registry.setSendBufferSizeLimit(512 * 1024); //发送缓冲区的最大大小限制
}
@Bean
public HandshakeInterceptor handshakeInterceptor() {
return new StaffHandshakeInterceptor();
}
}
@Slf4j
public class StaffHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
log.info("WebSocket 握手连接前处理");
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
log.info("WebSocket 握手连接后处理");
}
}