Websocket 在Springboot中使用
阿新 • • 發佈:2018-11-02
在之前的專案中使用過H5的websocket,但是在移植到Springboot專案中時,發現和之前的用法有略微差別,主要是
在@ServerEndpoint管理分配上。
一、在非Springboot專案裡,使用websocket要在pom檔案中引入javaee標準
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope >provided</scope>
</dependency>
websocket伺服器端直接新增@ServerEndpoint註解宣告,然後保證前端websocke路徑一致即可
@ServerEndpoint("/websocket}")
public class WebSocketServer {
...
}
二、而在Springboot專案中,就不需要引入javaee-api了,spring-boot已經包含了。
使用springboot的websocket功能:
1、首先引入springboot元件。
<dependency >
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、注入ServerEndpointExporter
注入ServerEndpointExporter,這個bean會自動註冊使用了@ServerEndpoint註解宣告的Websocket endpoint。
要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內建容器,就不要注入ServerEndpointExporter,
因為它將由容器自己提供和管理。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、websocket的具體實現類
@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
...
}
使用springboot的唯一區別是要@Component宣告下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。
雖然@Component預設是單例模式的,但springboot還是會為每個websocket連線初始化一個bean,所以可以用一個靜態set儲存起來。
4、前端程式碼保證websocket地址一致
websocket = new WebSocket("ws://localhost:8080/websocket");