在之前浏览器还不支持WebSocket的时候,Web开发者大多使用轮询接口的方式来实现近实时的数据更新。这种单方向通信的方式,由于服务器是被动接受查询,只能实现近实时的消息更新,且轮询的频率很难准确确定,如果频率高势必会增加服务器的负担;如果频率低,服务器端的消息可能很有很长的延迟才能达到客户端。
如今,web3.0时代的到来,几乎所有的浏览器和Web服务器均支持了WebSocket。WebSocket的产生正式为了解决客户端与Web服务器之间单向通信的问题。WebSocket实现了浏览器(客户端)与Web服务器的双向通信,建立连接之后任何一方都可以主动发送消息到对方。
Spring Boot提供了WebSocket的自动化配置,按照下面的步骤即可快速的将WebSocket整合到项目中。
本文使用的环境如下:
- Spring Boot:2.6.6
- JDK:11.0.2
1.引入依赖Starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 编写WebSocket消息处理器
首先介绍一下WebSocketHandler接口,此接口用于处理连接的生命周期事件和消息处理:
package org.springframework.web.socket;
/**
* A handler for WebSocket messages and lifecycle events.
*/
public interface WebSocketHandler {
/**
* WebSocket连接建立成功被调用,可在此处保存会话信息。
*/
void afterConnectionEstablished(WebSocketSession session) throws Exception;
/**
* 当消息到达时调用,可在此处处理消息。
*/
void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
/**
* 当底层的消息传输发生错误时被调用。
*/
void handleTransportError(WebSocketSession session, Throwable exception) throws Exception;
/**
* 当连接被任何一方关闭时,或者发生传输错误后被调用。
*/
void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
/**
* 是否支持部分(不完整)消息。
*/
boolean supportsPartialMessages();
}
实现自己的Handler:
import com.github.cloudgyb.websocket.config.WebSocketEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler