前言
我们在项目中可能会遇到这样的场景,平台接收到的信息实时发布给所有的用户,其实就是后端主动向前端广播消息。
这样的场景可以让前端轮询实现,但是要达到接近实时获取信息的效果就需要前端短周期的轮询,HTTP请求包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源,周期越短服务器压力越大,如果用户量太大的话就杯具了。所以小编就想到了WebSocket和长轮询都是比较合适实现方式。这里将webSocket进行代码演示。
实践
一、引入maven依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
二、为了使服务器能引入ioc对象,准备工作
这里借鉴了stackoverflow的处理方式
https://stackoverflow.com/questions/30483094/springboot-serverendpoint-failed-to-find-the-root-webapplicationcontext
public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
/**
* Spring application context.
*/
private static volatile BeanFactory context;
@Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
return context.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CustomSpringConfigurator.context = applicationContext;
}
}
@ConditionalOnWebApplication
@Configuration
public class WebSocketConfigurator {
/**
*This is just to get context
*/
@Bean
public CustomSpringConfigurator customSpringConfigurator() {
return new CustomSpringConfigurator();
}
}
@Component
public class WebSocketConfig {
/**
* ServerEndpointExporter 作用
* <p>
* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
*打包后项目不再依赖内置tomcat 会导致报错
* @return 作用
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
三、服务器对接client端代码(这里演示初始化的时候向client端推送数据)
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}", configurator = CustomSpringConfigurator.class)
public class WebSocket {
@Resource
private OrderDetailService orderDetailService;
/**
* 与某个客户端的连接对话,需要通过它来给客户端发送消息
*/
private Session session;
/**
* 标识当前连接客户端的用户名
*/
private String userId;
/**
* 用于存所有的连接服务的客户端,这个对象存储是安全的
*/
private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
this.session = session;
this.userId = userId;
// name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
webSocketMap.put(userId, this);
List<OrderDetail> list = orderDetailService.list();
groupSending(com.alibaba.fastjson.JSON.toJSONString(list));
log.info("[WebSocket] 连接成功,当前连接人数为:={}", webSocketMap.size());
}
@OnClose
public void onClose() {
webSocketMap.remove(this.userId);
log.info("[WebSocket] 退出成功,当前连接人数为:={}", webSocketMap.size());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("[WebSocket] 收到消息:{}", message);
//可以群发消息
//消息保存到数据库、redis
if(StringUtils.isNotBlank(message)){
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId",this.userId);
String toUserId=jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){
webSocketMap.get(toUserId).groupSending(jsonObject.toJSONString());
}else{
log.error("请求的userId:"+toUserId+"不在该服务器上");
//否则不在这个服务器上,发送到mysql或者redis
}
}catch (Exception e){
log.error("send message fail", e);
}
}
}
/**
* 群发
*
* @param message 消息
*/
public void groupSending(String message) {
for (String userId : webSocketMap.keySet()) {
try {
webSocketMap.get(userId).session.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("userId send {},message is {}", userId, message);
}
}
}
/**
* 指定发送
*
* @param userId 用户id
* @param message 消息
*/
public void appointSending(String userId, String message) {
try {
webSocketMap.get(userId).session.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("{} send message fail",userId, e);
}
}
}
四、定义web的html页面index.html
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8085/websocket/12");
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event) {
//setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
内部推送:
项目目录结构
查看演示效果