springboot整合websocket出现的问题记录与解决方式

1.整合websocket后启动报错:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method springAsyncExecutor in org.activiti.spring.boot.AbstractProcessEngineAutoConfiguration required a single bean, but 4 were found:
	- clientInboundChannelExecutor: defined by method 'clientInboundChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
	- clientOutboundChannelExecutor: defined by method 'clientOutboundChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
	- brokerChannelExecutor: defined by method 'brokerChannelExecutor' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]
	- messageBrokerTaskScheduler: defined by method 'messageBrokerTaskScheduler' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

分析:根据提示我们可以看出,这是Websocket自动配置类中的一个错误。它依赖于它们TaskExecutor在应用程序上下文中唯一的一个bean,或者如果有多个bean,则它们中的一个是主要的。而此时并没有声明主要的TaskExecutorBean。

解决方法:所以应该能够通过声明自己的TaskExecutorbean并将其标记为@Primary;解决该问题。即在application中声明一个主要的TaskExecutorBean。

    @Primary
    @Bean
    public TaskExecutor primaryTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        return executor;
    }

结论:使用该方式后项目启动没有再出错了。

 

2.与前端进行websocket调试时报Error during WebSocket handshake: Unexpected response code: 200的错误(前端使用h5的WebSocket)

分析:通过网上查询发现这是因为后台将该请求视为了一个普通的http请求,从而造成了这种错误。查看后端代码发现在websocket配置时:

@Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //注册一个Stomp的节点(endpoint),并指定使用SockJS协议。记得设置跨域
        stompEndpointRegistry.addEndpoint("/endpointAric")
                .setAllowedOrigins("*")
                .withSockJS();
    }

发现将这个stomp节点的访问协议设置成了SockJs,由此原生的访问方式被视为了http请求,并没有返回想要code: 101而是返回的200。

解决方法:所以去掉withSockJS()这句代码,重新启动即可。

结论:重新启动后websocket连接成功。

你可能感兴趣的:(springboot整合websocket出现的问题记录与解决方式)