一般前端请求服务器接口都是使用主动请求的模式,有ajax等。但分不同使用场景 有不一样的需求, 比如要求实时性比较高的场景使用ajax则不好实现,且实现了开销也大。所以有了websocket这种长链接的形式保持在前端与服务器的通信协议。
现在很多后端框架都使用springboot,那么如何在springboot中整合websocket服务呢?直接上代码,更加清晰明了!
首先 在 pom 中加入 websocket 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
创建 socketConfig.class 配置类
@Configuration
public class SocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
创建 websocket.class 接口服务类
注意需要声明为@Component ,这样springboot才会注入并管理
@Component
@ServerEndpoint(value = "/webSocket"