有个需求是要轮询redis上的实时数据并返回前端,打算直接就用WebSocket解决了。
依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置类:
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
服务:
@ServerEndpoint("/canMonitor")
@Component
public class WebSocketServer {
// 这里使用静态,让 redisTemplate 属于类
private static RedisTemplate redisTemplate;
// 注入的时候,给类的 redisTemplate 注入
@Autowired
public void setRedisTemplate(RedisTemplate redisTemplate) {
WebSocketServer.redisTemplate = redisTemplate;
}
private Logger log= LoggerFactory.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
long interval;
long endTime;
JSONObject msg = JSONObject.parseObject(message);
if (msg.get("interval") != null) {
interval = Long.valueOf(msg.get("interval").toString());
} else {
interval = 3000;
}
if (msg.get("duration") != null) {
endTime = Long.valueOf(msg.get("duration").toString()) + System.currentTimeMillis();
} else {
endTime = 180000 + System.currentTimeMillis();
}
if (msg.get("busId") != null) {
while (System.currentTimeMillis() <= endTime) {
try {
Object canData = redisTemplate.opsForHash().entries("test").get(msg.get("busId").toString());
sendMessage(canData.toString());
Thread.sleep(interval);
} catch (Exception e) {
e.printStackTrace();
log.error("推送can数据失败:{}", e.getMessage());
break;
}
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
前端调试页面:
<script type="text/javascript">
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
// socket = new WebSocket("ws://localhost:11002/canMonitor");
var data = {
"id": 3011746,
"duration": 1000*30,
"interval": 5000
};
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
socket.send(JSON.stringify(data));
};
//获得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
遇到的问题
- WebSocketServer类中,直接通过@Autowired注入的类都会报nullpoiterException
解决方法:将要注入的 service 改成 static,就不会为null了。 - 如果路径经过公网那边转过来的话,会无法连接上
引用:https://blog.csdn.net/moshowgame/article/details/80275084
https://blog.csdn.net/m0_37202351/article/details/86255132