基于spring @EnableWebSocket 实现socket通信业务处理优化

本篇文章针对基于spring @EnableWebSocket 实现socket通信业务处理的处理

在socket通信默认情况下是线程不安全的,当多个线程访问同一个socket实体是将会发生错误,具体看源码当socket发送信息是改变自身状态,当另一个线程发送时会检查状态,当状态不为初始值是将抛出异常,

本人解决思路是将每个socket客户端的信息根据放到单独队列去处理,以实现单线程操作

不涉及socket存储处理以及发送的逻辑代码

 

首先定义消息实体类封装收到的消息

public class MessageCheckBean {
    /*
     1 open 2 message 3 close 4 error
     */
    private Integer msgType;
    private WebSocketSession session;
    private String msg;
    private CloseReason closeReason;
    private Throwable throwable;
    public Integer getMsgType() {
        return msgType;
    }

    public void setMsgType(Integer msgType) {
        this.msgType = msgType;
    }

    public WebSocketSession getSession() {
        return session;
    }

    public void setSession(WebSocketSession session) {
        this.session = session;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public CloseReason getCloseReason() {
        return closeReason;
    }

    public void setCloseReason(CloseReason closeReason) {
        this.closeReason = closeReason;
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public void setThrowable(Throwable throwable) {
        this.throwable = throwable;
    }

然后首先消息队列以及线程池管理逻辑,讲接收消息和发送消息分开

/**
 * 消息队列以及线程池管理
 */
public class MsgCheckSessionQueueManager {

    private static boolean openAll = false;
    private static boolean closeAllThread = false;
    /*
    原始数据队列
     */
    private static LinkedBlockingQueue<MessageCheckBean> rowBlockingQueue = new LinkedBlockingQueue();
    private static ArrayList<LinkedBlockingQueue<UserMsg>> needSendMsgArray = new ArrayList<>();
    static {
        needSendMsgArray.add(new LinkedBlockingQueue<>());
        needSendMsgArray.add(new LinkedBlockingQueue<>());
        needSendMsgArray.add(new LinkedBlockingQueue<>());
    }
    //实际生产请使用其他线程池
    private static ExecutorService sendMsgCacheThreadPool = new ThreadPoolExecutor(needSendMsgArray.size(), needSendMsgArray.size(),
            20L, TimeUnit.SECONDS,
            new Synchronou
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值