创建WebSocket工具类
package org.jmis.riskassess.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint(value = "/message-service")
public class WebSocketUtil {
private static final ConcurrentHashMap sessions = new ConcurrentHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);
public static void pushMessage(String userId, String message) {
Session session = sessions.get(userId);
if (session != null && session.isOpen()) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
logger.error("Failed to send message to userId: " + userId, e);
}
} else {
// 会话失效,从会话集合中移除
sessions.remove(userId, session);
// logger.warn("Session is invalid for userId: " + userId + ", removing from sessions");
}
}
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
Map> queryParams = session.getRequestParameterMap();
String userId = queryParams.get("userId").get(0);
sessions.put(userId, session);
logger.info("WebSocket opened: " + session.getId() + ", userId: " + userId);
}
@OnClose
public void onClose(Session session) {
String closedSessionId = session.getId();
sessions.entrySet().removeIf(entry -> entry.getValue().getId().equals(closedSessionId));
logger.info("WebSocket closed: " + closedSessionId);
}
@OnMessage
public void onMessage(String message, Session session) {
String userId = (String) session.getUserProperties().get("userId");
if (userId == null) {
session.getUserProperties().put("userId", message);
logger.info("User ID saved: " + message);
}
}
public static int getSessionCount() {
return sessions.size();
}
public static int getOpenConnectionCount() {
int openConnectionCount = 0;
for (Session session : sessions.values()) {
if (session.isOpen()) {
openConnectionCount++;
}
}
return openConnectionCount;
}
public static List getOpenConnections() {
List openConnections = new ArrayList<>();
for (Session session : sessions.values()) {
if (session.isOpen()) {
openConnections.add(session);
}
}
return openConnections;
}
}
创建WebSocket配置文件
package org.jmis.riskassess.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
业务逻辑
package org.jmis.riskassess.safeSystemDataTask;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jmis.riskassess.config.WebSocketUtil;
import org.jmis.riskassess.entity.Message;
import org.jmis.riskassess.entity.MessageUser;
import org.jmis.riskassess.pojo.MessageInfo;
import org.jmis.riskassess.pojo.MineFoundation;
import org.jmis.riskassess.service.IMessageService;
import org.jmis.riskassess.service.IMessageUserService;
import org.jmis.riskassess.vo.AlarmRealtimeVO;
import org.jmis.riskassess.vo.DzAlarmAcceptVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springjmis.core.tool.utils.Func;
import org.springjmis.core.tool.utils.ObjectUtil;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class MessagePushTask {
@Autowired
private WebSocketUtil webSocketUtil;
@Autowired
private IMessageUserService messageUserService;
@Autowired
private IMessageService messageService;
@Scheduled(fixedDelay = 10000) // 每10秒执行一次
public void pushUnreadMessages() {
// 查询未读消息的用户以及消息内容
List