在之前的项目中使用过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");