记一次LinkedBlockingQueue的使用并且发送socket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | package cn.xs.qishi.socket.standalone.queue; import cn.xs.qishi.cache.dto.topic.StatSendMsg; import cn.xs.qishi.socket.standalone.session.StatSocketSessionManager; import lombok.CustomLog; import javax.websocket.EncodeException; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; import java.io.IOException; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; /** * 统计阻塞对了 * * @author liuxn * @date 2022/6/23 */ @CustomLog public class StatTopicHandler { private static StatTopicHandler handler = null ; private static LinkedBlockingQueue<StatSendMsg> queue = new LinkedBlockingQueue(); private StatSocketSessionManager sessionManager; public static StatTopicHandler getInstance() { if (handler == null ) { handler = new StatTopicHandler(); } return handler; } public void setSessionManager(StatSocketSessionManager sessionManager) { this .sessionManager = sessionManager; } public StatTopicHandler() { Thread thread = new Thread( new StatQueueThread()); thread.setName( "stat_redis_topic_consumer" ); thread.start(); log.info( ">> 业务统计阻塞队列监听启动完毕 !!!" ); } public void put(StatSendMsg msg) { try { queue.put(msg); } catch (InterruptedException e) { log.error( ">> 统计消息放入阻塞队列异常" , e); } } class StatQueueThread implements Runnable { private boolean isRun = true ; @Override public void run() { while (isRun) { try { StatSendMsg msg = queue.take(); long userId = msg.getUserId(); String msgId = msg.getMsgId(); List<Session> list = sessionManager.user(userId); int sent = 0 ; log.info( ">> 阻塞队列中 redis topic 消息:" + msgId); for (Session session : list) { try { RemoteEndpoint.Basic basicRemote = session.getBasicRemote(); basicRemote.sendObject(msg); String sessionId = session.getId(); log.info( ">> Sent stat msg to client.sessionId:{},msgId:{},userId:{}" , sessionId, msgId, userId); sent++; } catch (IOException | EncodeException e) { log.error( "发送消息异常" , e); if (!session.isOpen()) { sessionManager.remove(session, userId); } } } if (sent == 0 ) { log.info( ">> Sent stat msg to client fail. no client userid:[{}]" , userId); } } catch (InterruptedException e) { log.error( ">>阻塞队列 监听异常" , e); } } } public void stop() { isRun = false ; } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!