本篇文章针对基于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