解决springboot启动报 Failed to start bean 'subProtocolWebSocketHandler'; nested exception is java.lang.IllegalArgumentException: No handlers
- 问题发现
- 问题解决
问题发现
使用springboot整合websocket,启动时报错,示例代码:
@EnableWebSocket
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(myWebSocketHandler(),"/ws").addInterceptors(new MyHandshakeInterceptor());
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxBinaryMessageBufferSize(8192); // 设置二进制消息缓冲区大小
container.setMaxTextMessageBufferSize(8192); // 设置文本消息缓冲区大小
container.setAsyncSendTimeout(5000l); // 设置异步发送超时时间(毫秒)
// 其他配置项...
return container;
}
}
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的文本消息
String payload = message.getPayload();
System.out.println("接收到消息:" + payload);
// 发送响应消息
session.sendMessage(new TextMessage("Hello, client!"));
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// WebSocket 连接建立时执行的操作
System.out.println("WebSocket 连接已建立");
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// WebSocket 连接关闭时执行的操作
System.out.println("WebSocket 连接已关闭");
}
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfigurer implements WebSocketMessageBrokerConfigurer {
}
如图所示:
问题解决
在上述代码中可以看到有两个注解,@EnableWebSocketMessageBroker
和 @EnableWebSocket
,同时使用,导致配置错误引起的。由于这两个注解都启用了 WebSocket 功能,因此同时使用它们可能会导致冲突。
两者取其一即可,我们将@EnableWebSocketMessageBroker
删掉,暂时不用基于消息代理。重新启动后,如图: