一:实现消息实时通知
实现消息的实时通知有2种方案:即推和拉。拉,就是页面用Ajax去轮询访问后台是否有新的消息但是资源消耗很大,推即服务器通过“长链接”去实时推送消息去前端页面主要的实现就是使用WwbSocket。
这里,我们使用的是springboot2.0.x版本来整合WebScoket。
二:代码
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.配置Config
package com.config.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* WebSocket配置
*
* @author yueli.liao
* @date 2019-03-12 11:25
*/
@Configuration
public class WebSocketConfig {
/**
* 开启WebSocket功能
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.webSocket服务器
package com.config.websocket.service;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Sessi