解決SpringBoot 1.5 使用 websocket,junit,tomcat 衝突異常

解決SpringBoot 1.5 使用 websocket,junit,tomcat 衝突異常

一、編譯時,異常信息,可能原因是依賴包衝突,需要修改maven的作用範圍
java.lang.IllegalStateException: Failed to load ApplicationContext

解決方法
1.修改 pom 文件

<!-- websocket編譯時依賴tomcat容器,打成war包,外部運行環境不需要運行 -->
<!-- scope 包的範圍配置成 provided  -->
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <version>1.5.19.RELEASE</version>
        <scope>provided</scope>
</dependency>

<!-- 引入websocket 依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <scope>compile</scope>
</dependency>

<!-- 添加junit依賴包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2.修改junit啓動類

@RunWith(SpringRunner.class)
// 創建一個隨機端口的真實的server容器,進行junit測試
@SpringBootTest(classes = 啓動類入口.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// @SpringBootTest
public class TestApplicationTests

二、部署時,異常信息
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serverEndpointExporter' defined in class path resource [com/jdrx/install/config/WebSocketConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available

原因分析:可能是 由於 ServerContainer 和tomcat版本有衝突,無法被實例化,所以無法啓動,

解決方法:
升級 Tomcat 版本爲 8.5.51

三、部署後訪問 ws:// 404 錯誤
異常信息:
Error during WebSocket handshake: Unexpected response code: 404"

問題原因:可能是由於nginx的ws:// 協議支持沒有配置

解決方案:
修改nginx配置:
server {
                location / {
                    # ws:// 協議支持
                    proxy_http_version 1.1;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection "upgrade";
                }
}

建議升級到 Springboot 2.x 版本

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章