干燥机配套车间生产管理系统/云平台服务端
bsw215583320
2024-04-16 c2fccb01b972176dc3da5a497b5e904025e9e98d
jeecg-module-dry/jeecg-module-dry-biz/src/main/java/org/jeecg/modules/dry/websocket/DrySocket.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,146 @@
package org.jeecg.modules.dry.websocket;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.WebsocketConst;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
 * @Author scott
 * @Date 2019/11/29 9:41
 * @Description: æ­¤æ³¨è§£ç›¸å½“于设置访问URL
 */
@Component
@Slf4j
@ServerEndpoint("/drySocket/{tenantId}")
public class DrySocket {
    /**线程安全Map*/
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();
    //==========【websocket接受、推送消息等方法 â€”— å…·ä½“服务节点推送ws消息】========================================================================================
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "tenantId") String tenantId) {
        try {
            sessionPool.put(tenantId, session);
            log.info("【系统 WebSocket】有新的连接,总数为:" + sessionPool.size());
        } catch (Exception e) {
        }
    }
    @OnClose
    public void onClose(@PathParam("tenantId") String tenantId) {
        try {
            sessionPool.remove(tenantId);
            log.info("【系统 WebSocket】连接断开,总数为:" + sessionPool.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * ws推送消息
     *
     * @param tenantId
     * @param message
     */
    public void pushMessage(String tenantId, String message) {
        for (Map.Entry<String, Session> item : sessionPool.entrySet()) {
            //userId key值= {用户id + "_"+ ç™»å½•token的md5串}
            //TODO vue2未改key新规则,暂时不影响逻辑
            if (item.getKey().contains(tenantId)) {
                Session session = item.getValue();
                try {
                    //update-begin-author:taoyan date:20211012 for: websocket报错 https://gitee.com/jeecg/jeecg-boot/issues/I4C0MU
                    synchronized (session){
                        log.info("【系统 WebSocket】推送单人消息:" + message);
                        session.getBasicRemote().sendText(message);
                    }
                    //update-end-author:taoyan date:20211012 for: websocket报错 https://gitee.com/jeecg/jeecg-boot/issues/I4C0MU
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
        }
    }
    /**
     * ws遍历群发消息
     */
    public void pushMessage(String message) {
        try {
            for (Map.Entry<String, Session> item : sessionPool.entrySet()) {
                try {
                    item.getValue().getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            log.info("【系统 WebSocket】群发消息:" + message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    /**
     * ws接受客户端消息
     */
    @OnMessage
    public void onMessage(String message, @PathParam(value = "tenantId") String tenantId) {
        if(!"ping".equals(message) && !WebsocketConst.CMD_CHECK.equals(message)){
            log.info("【系统 WebSocket】收到客户端消息:" + message);
        }else{
            log.debug("【系统 WebSocket】收到客户端消息:" + message);
        }
//        //------------------------------------------------------------------------------
//        JSONObject obj = new JSONObject();
//        //业务类型
//        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
//        //消息内容
//        obj.put(WebsocketConst.MSG_TXT, "心跳响应");
//        this.pushMessage(userId, obj.toJSONString());
//        //------------------------------------------------------------------------------
    }
    /**
     * é…ç½®é”™è¯¯ä¿¡æ¯å¤„理
     *
     * @param session
     * @param t
     */
    @OnError
    public void onError(Session session, Throwable t) {
        log.warn("【系统 WebSocket】消息出现错误");
        t.printStackTrace();
    }
    //==========【系统 WebSocket接受、推送消息等方法 â€”— å…·ä½“服务节点推送ws消息】========================================================================================
    //==========【采用redis发布订阅模式——推送消息】========================================================================================
    /**
     * æ­¤ä¸ºå•点消息(多人) redis
     *
     * @param userIds
     * @param message
     */
//    public void sendMessage(String[] userIds, String message) {
//        for (String userId : userIds) {
//            sendMessage(userId, message);
//        }
//    }
    //=======【采用redis发布订阅模式——推送消息】==========================================================================================
}