Browse Source

just format code style

deason 3 years ago
parent
commit
0a704d4b84

+ 68 - 70
src/main/java/cn/com/qmth/examcloud/ws/api/provider/WsCloudServiceProvider.java

@@ -1,18 +1,5 @@
 package cn.com.qmth.examcloud.ws.api.provider;
 
-import javax.websocket.Session;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.logging.log4j.ThreadContext;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.api.commons.security.bean.UserType;
 import cn.com.qmth.examcloud.commons.exception.StatusException;
@@ -23,70 +10,81 @@ import cn.com.qmth.examcloud.ws.api.response.SendTextResp;
 import cn.com.qmth.examcloud.ws.starter.core.MessageOut;
 import cn.com.qmth.examcloud.ws.starter.core.SessionInfo;
 import cn.com.qmth.examcloud.ws.starter.core.WebSocketHelper;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSyntaxException;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.ThreadContext;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.websocket.Session;
 
 @Api(tags = "websocket服务")
 @RestController
 @RequestMapping("api/cloud/ws")
 public class WsCloudServiceProvider implements WsCloudService {
 
-	private static final long serialVersionUID = 4784116669909937047L;
-
-	@ApiOperation(value = "发送消息")
-	@PostMapping("sendText")
-	@Override
-	public SendTextResp sendText(@RequestBody SendTextReq req) {
-
-		Long rootOrgId = req.getRootOrgId();
-		UserType userType = req.getUserType();
-		Long userId = req.getUserId();
-		String path = req.getPath();
-		String eventId = req.getEventId();
-		String content = req.getContent();
-
-		User user = new User();
-		user.setUserType(userType);
-		user.setUserId(userId);
-		user.setRootOrgId(rootOrgId);
-		String key = user.buildKey();
-
-		Session session = WebSocketHelper.getSession(path, key);
-
-		if (null == session) {
-			throw new StatusException("100001", "no ws session about path [" + path + "]");
-		}
-
-		SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
-
-		if (null == sessionInfo) {
-			throw new StatusException("100002", "no ws session info");
-		}
-
-		MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
-		out.setEventId(eventId);
-
-		JsonElement jsonEl = null;
-		if (StringUtils.isNotBlank(content)) {
-			try {
-				jsonEl = JsonParser.parseString(content);
-			} catch (JsonSyntaxException e) {
-				throw new StatusException("100003", "message is not a json string");
-			}
-		}
-
-		out.setContent(jsonEl);
-
-		try {
-			ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
-			WebSocketHelper.sendText(session, path, out);
-		} finally {
-			ThreadContext.put("TRACE_ID", ThreadLocalUtil.getTraceId());
-		}
-
-		SendTextResp resp = new SendTextResp();
-		resp.setSessionId(sessionInfo.getSessionId());
-		return resp;
-	}
+    private static final long serialVersionUID = 4784116669909937047L;
+
+    @ApiOperation(value = "发送消息")
+    @PostMapping("sendText")
+    @Override
+    public SendTextResp sendText(@RequestBody SendTextReq req) {
+
+        Long rootOrgId = req.getRootOrgId();
+        UserType userType = req.getUserType();
+        Long userId = req.getUserId();
+        String path = req.getPath();
+        String eventId = req.getEventId();
+        String content = req.getContent();
+
+        User user = new User();
+        user.setUserType(userType);
+        user.setUserId(userId);
+        user.setRootOrgId(rootOrgId);
+        String key = user.buildKey();
+
+        Session session = WebSocketHelper.getSession(path, key);
+
+        if (null == session) {
+            throw new StatusException("100001", "no ws session about path [" + path + "]");
+        }
+
+        SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
+
+        if (null == sessionInfo) {
+            throw new StatusException("100002", "no ws session info");
+        }
+
+        MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
+        out.setEventId(eventId);
+
+        JsonElement jsonEl = null;
+        if (StringUtils.isNotBlank(content)) {
+            try {
+                jsonEl = JsonParser.parseString(content);
+            } catch (JsonSyntaxException e) {
+                throw new StatusException("100003", "message is not a json string");
+            }
+        }
+
+        out.setContent(jsonEl);
+
+        try {
+            ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
+            WebSocketHelper.sendText(session, path, out);
+        } finally {
+            ThreadContext.put("TRACE_ID", ThreadLocalUtil.getTraceId());
+        }
+
+        SendTextResp resp = new SendTextResp();
+        resp.setSessionId(sessionInfo.getSessionId());
+        return resp;
+    }
 
 }

+ 39 - 45
src/main/java/cn/com/qmth/examcloud/ws/starter/api/controller/WebSocketController.java

@@ -1,19 +1,5 @@
 package cn.com.qmth.examcloud.ws.starter.api.controller;
 
-import javax.websocket.Session;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.logging.log4j.ThreadContext;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.commons.exception.StatusException;
 import cn.com.qmth.examcloud.commons.util.JsonUtil;
@@ -23,51 +9,59 @@ import cn.com.qmth.examcloud.web.support.WithoutStackTrace;
 import cn.com.qmth.examcloud.ws.starter.core.MessageOut;
 import cn.com.qmth.examcloud.ws.starter.core.SessionInfo;
 import cn.com.qmth.examcloud.ws.starter.core.WebSocketHelper;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSyntaxException;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.ThreadContext;
+import org.springframework.web.bind.annotation.*;
+
+import javax.websocket.Session;
 
 @RestController
 @RequestMapping("api/ctr/ws")
 public class WebSocketController extends ControllerSupport {
 
-	@WithoutStackTrace
-	@PostMapping("{path}")
-	public String post(@PathVariable String path, @RequestBody String message) {
+    @WithoutStackTrace
+    @PostMapping("{path}")
+    public String post(@PathVariable String path, @RequestBody String message) {
 
-		User accessUser = getAccessUser();
+        User accessUser = getAccessUser();
 
-		Session session = WebSocketHelper.getSession(path, accessUser.getKey());
+        Session session = WebSocketHelper.getSession(path, accessUser.getKey());
 
-		if (null == session) {
-			throw new StatusException("100001", "no ws session about path [" + path + "]");
-		}
+        if (null == session) {
+            throw new StatusException("100001", "no ws session about path [" + path + "]");
+        }
 
-		SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
+        SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
 
-		if (null == sessionInfo) {
-			throw new StatusException("100002", "no ws session info");
-		}
+        if (null == sessionInfo) {
+            throw new StatusException("100002", "no ws session info");
+        }
 
-		MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
+        MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
 
-		JsonElement jsonEl = null;
-		if (StringUtils.isNotBlank(message)) {
-			try {
-				jsonEl = JsonParser.parseString(message);
-			} catch (JsonSyntaxException e) {
-				throw new StatusException("100003", "message is not a json string");
-			}
-		}
+        JsonElement jsonEl = null;
+        if (StringUtils.isNotBlank(message)) {
+            try {
+                jsonEl = JsonParser.parseString(message);
+            } catch (JsonSyntaxException e) {
+                throw new StatusException("100003", "message is not a json string");
+            }
+        }
 
-		out.setContent(jsonEl);
+        out.setContent(jsonEl);
 
-		try {
-			ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
-			WebSocketHelper.sendText(session, path, out);
-		} finally {
-			ThreadContext.put("TRACE_ID", ThreadLocalUtil.getTraceId());
-		}
+        try {
+            ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
+            WebSocketHelper.sendText(session, path, out);
+        } finally {
+            ThreadContext.put("TRACE_ID", ThreadLocalUtil.getTraceId());
+        }
 
-		String json = JsonUtil.toJson(out);
-		return json;
-	}
+        String json = JsonUtil.toJson(out);
+        return json;
+    }
 
 }

+ 144 - 147
src/main/java/cn/com/qmth/examcloud/ws/starter/core/WebSocketHelper.java

@@ -1,21 +1,18 @@
 package cn.com.qmth.examcloud.ws.starter.core;
 
-import java.util.Date;
-import java.util.Map;
-
-import javax.websocket.Session;
-
-import org.apache.commons.io.IOUtils;
-
-import com.google.common.collect.Maps;
-
 import cn.com.qmth.examcloud.api.commons.security.bean.User;
 import cn.com.qmth.examcloud.api.commons.security.bean.UserType;
 import cn.com.qmth.examcloud.commons.util.JsonUtil;
 import cn.com.qmth.examcloud.commons.util.StringUtil;
+import com.google.common.collect.Maps;
+import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.websocket.Session;
+import java.util.Date;
+import java.util.Map;
+
 /**
  * WebSocket helper
  *
@@ -25,143 +22,143 @@ import org.slf4j.LoggerFactory;
  */
 public class WebSocketHelper {
 
-	private static final Logger LOG = LoggerFactory.getLogger(WebSocketHelper.class);
-
-	private static final Map<String, Session> INDEX_MAP = Maps.newConcurrentMap();
-
-	private static final Map<Session, SessionInfo> SESESION_INFO_MAP = Maps.newConcurrentMap();
-
-	/**
-	 * 重新设置session
-	 *
-	 * @author WANGWEI
-	 * @param path
-	 * @param user
-	 * @param session
-	 * @param sessionId
-	 */
-	public static void setSession(String path, User user, Session session, String sessionId) {
-
-		String index = user.getKey() + ":" + path;
-		Session oldSession = INDEX_MAP.get(index);
-		if (null != oldSession && !oldSession.equals(session)) {
-			SESESION_INFO_MAP.remove(oldSession);
-			IOUtils.closeQuietly(oldSession);
-		}
-
-		INDEX_MAP.put(index, session);
-
-		SessionInfo si = new SessionInfo();
-		si.setIndex(index);
-		si.setUser(user);
-		si.setSessionId(sessionId);
-
-		SESESION_INFO_MAP.put(session, si);
-
-	}
-
-	/**
-	 * 关闭 session
-	 *
-	 * @author WANGWEI
-	 * @param session
-	 */
-	public static void closeSession(Session session) {
-		SessionInfo si = SESESION_INFO_MAP.get(session);
-
-		if (null != si) {
-			INDEX_MAP.remove(si.getIndex());
-		}
-
-		SESESION_INFO_MAP.remove(session);
-
-		IOUtils.closeQuietly(session);
-	}
-
-	/**
-	 * 获取 session
-	 *
-	 * @author WANGWEI
-	 * @param path
-	 * @param key
-	 * @return
-	 */
-	public static Session getSession(String path, String key) {
-		String index = key + ":" + path;
-		Session session = INDEX_MAP.get(index);
-		return session;
-	}
-
-	/**
-	 * 获取 session
-	 *
-	 * @author WANGWEI
-	 * @param path
-	 * @param rootOrgId
-	 * @param userType
-	 * @param userId
-	 * @return
-	 */
-	public static Session getSession(String path, Long rootOrgId, UserType userType, Long userId) {
-
-		String key = StringUtil.join("U_", userType.getCode(), "_", rootOrgId, "_", userId);
-
-		return getSession(path, key);
-	}
-
-	/**
-	 * 获取 SessionInfo
-	 *
-	 * @author WANGWEI
-	 * @param session
-	 * @return
-	 */
-	public static SessionInfo getSessionInfo(Session session) {
-		return SESESION_INFO_MAP.get(session);
-	}
-
-	/**
-	 * 发送消息
-	 *
-	 * @author WANGWEI
-	 * @param session
-	 * @param path
-	 * @param out
-	 */
-	public static void sendText(Session session, String path, MessageOut out) {
-		try {
-			out.setDate(new Date());
-			String message = JsonUtil.toJson(out);
-			if (LOG.isDebugEnabled()) {
-				LOG.debug("[sendText]. path=" + path + "; message=" + message);
-			}
-			session.getBasicRemote().sendText(message);
-		} catch (Exception e) {
-			LOG.error("[sendText-FAIL]. path=" + path, e);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-	}
-
-	/**
-	 * 发送消息
-	 *
-	 * @author WANGWEI
-	 * @param session
-	 * @param path
-	 * @param out
-	 */
-	public static void sendText(Session session, String path, String out) {
-		try {
-			if (LOG.isDebugEnabled()) {
-				LOG.error("[sendText]. path=" + path + "; message=" + out);
-			}
-			session.getBasicRemote().sendText(out);
-		} catch (Exception e) {
-			LOG.error("[sendText-FAIL]. path=" + path, e);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-	}
+    private static final Logger LOG = LoggerFactory.getLogger(WebSocketHelper.class);
+
+    private static final Map<String, Session> INDEX_MAP = Maps.newConcurrentMap();
+
+    private static final Map<Session, SessionInfo> SESESION_INFO_MAP = Maps.newConcurrentMap();
+
+    /**
+     * 重新设置session
+     *
+     * @param path
+     * @param user
+     * @param session
+     * @param sessionId
+     * @author WANGWEI
+     */
+    public static void setSession(String path, User user, Session session, String sessionId) {
+
+        String index = user.getKey() + ":" + path;
+        Session oldSession = INDEX_MAP.get(index);
+        if (null != oldSession && !oldSession.equals(session)) {
+            SESESION_INFO_MAP.remove(oldSession);
+            IOUtils.closeQuietly(oldSession);
+        }
+
+        INDEX_MAP.put(index, session);
+
+        SessionInfo si = new SessionInfo();
+        si.setIndex(index);
+        si.setUser(user);
+        si.setSessionId(sessionId);
+
+        SESESION_INFO_MAP.put(session, si);
+
+    }
+
+    /**
+     * 关闭 session
+     *
+     * @param session
+     * @author WANGWEI
+     */
+    public static void closeSession(Session session) {
+        SessionInfo si = SESESION_INFO_MAP.get(session);
+
+        if (null != si) {
+            INDEX_MAP.remove(si.getIndex());
+        }
+
+        SESESION_INFO_MAP.remove(session);
+
+        IOUtils.closeQuietly(session);
+    }
+
+    /**
+     * 获取 session
+     *
+     * @param path
+     * @param key
+     * @return
+     * @author WANGWEI
+     */
+    public static Session getSession(String path, String key) {
+        String index = key + ":" + path;
+        Session session = INDEX_MAP.get(index);
+        return session;
+    }
+
+    /**
+     * 获取 session
+     *
+     * @param path
+     * @param rootOrgId
+     * @param userType
+     * @param userId
+     * @return
+     * @author WANGWEI
+     */
+    public static Session getSession(String path, Long rootOrgId, UserType userType, Long userId) {
+
+        String key = StringUtil.join("U_", userType.getCode(), "_", rootOrgId, "_", userId);
+
+        return getSession(path, key);
+    }
+
+    /**
+     * 获取 SessionInfo
+     *
+     * @param session
+     * @return
+     * @author WANGWEI
+     */
+    public static SessionInfo getSessionInfo(Session session) {
+        return SESESION_INFO_MAP.get(session);
+    }
+
+    /**
+     * 发送消息
+     *
+     * @param session
+     * @param path
+     * @param out
+     * @author WANGWEI
+     */
+    public static void sendText(Session session, String path, MessageOut out) {
+        try {
+            out.setDate(new Date());
+            String message = JsonUtil.toJson(out);
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("[sendText]. path=" + path + "; message=" + message);
+            }
+            session.getBasicRemote().sendText(message);
+        } catch (Exception e) {
+            LOG.error("[sendText-FAIL]. path=" + path, e);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+    }
+
+    /**
+     * 发送消息
+     *
+     * @param session
+     * @param path
+     * @param out
+     * @author WANGWEI
+     */
+    public static void sendText(Session session, String path, String out) {
+        try {
+            if (LOG.isDebugEnabled()) {
+                LOG.error("[sendText]. path=" + path + "; message=" + out);
+            }
+            session.getBasicRemote().sendText(out);
+        } catch (Exception e) {
+            LOG.error("[sendText-FAIL]. path=" + path, e);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+    }
 
 }

+ 234 - 240
src/main/java/cn/com/qmth/examcloud/ws/starter/core/WebSocketServerEndpoint.java

@@ -1,20 +1,13 @@
 package cn.com.qmth.examcloud.ws.starter.core;
 
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.websocket.OnClose;
-import javax.websocket.OnError;
-import javax.websocket.OnMessage;
-import javax.websocket.OnOpen;
-import javax.websocket.Session;
-import javax.websocket.server.PathParam;
-import javax.websocket.server.ServerEndpoint;
-
+import cn.com.qmth.examcloud.api.commons.security.bean.User;
+import cn.com.qmth.examcloud.commons.exception.StatusException;
+import cn.com.qmth.examcloud.commons.util.JsonUtil;
+import cn.com.qmth.examcloud.web.redis.RedisClient;
+import cn.com.qmth.examcloud.web.support.SpringContextHolder;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonSyntaxException;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
@@ -23,15 +16,15 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-
-import cn.com.qmth.examcloud.api.commons.security.bean.User;
-import cn.com.qmth.examcloud.commons.exception.StatusException;
-import cn.com.qmth.examcloud.commons.util.JsonUtil;
-import cn.com.qmth.examcloud.web.redis.RedisClient;
-import cn.com.qmth.examcloud.web.support.SpringContextHolder;
+import javax.websocket.*;
+import javax.websocket.server.PathParam;
+import javax.websocket.server.ServerEndpoint;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * websocket ServerEndpoint
@@ -44,221 +37,222 @@ import cn.com.qmth.examcloud.web.support.SpringContextHolder;
 @Component
 public class WebSocketServerEndpoint {
 
-	private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerEndpoint.class);
-
-	private static RedisClient redisClient;
-
-	private static AtomicLong counter = new AtomicLong(0L);
-
-	private String sessionId;
-
-	private static RedisClient getRedisClient() {
-		if (null != redisClient) {
-			return redisClient;
-		}
-		redisClient = SpringContextHolder.getBean(RedisClient.class);
-		return redisClient;
-	}
-
-	@OnOpen
-	public void onOpen(Session session, @PathParam("path") String path) {
-		long amount = counter.incrementAndGet();
-
-		this.sessionId = UUID.randomUUID().toString().replace("-", "");
-
-		ThreadContext.put("TRACE_ID", sessionId);
-
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("[onOpen]. path=" + path + "; sessionsAmount=" + amount);
-		}
-
-		MessageOut out = new MessageOut(path, sessionId);
-		out.setEventId("open");
-
-		Method method = MessageHandlerHolder.getMethod(path);
-		if (null == method) {
-			out.setStatus("404", "NOT FOUND");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-
-		String key = getRequestParameter(session, "key");
-		String token = getRequestParameter(session, "token");
-
-		if (StringUtils.isBlank(key)) {
-			LOG.error("[onOpen-FAIL]. path=" + path + ". key is blank");
-			IOUtils.closeQuietly(session);
-			return;
-		}
-		if (StringUtils.isBlank(token)) {
-			LOG.error("[onOpen-FAIL]. path=" + path + ". token is blank");
-			IOUtils.closeQuietly(session);
-			return;
-		}
-
-		User user = getRedisClient().get(key, User.class);
-
-		if (null == user) {
-			out.setStatus("403", "no login");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		} else if (!token.equals(user.getToken())) {
-			out.setStatus("403", "token is wrong");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-
-		ThreadContext.put("CALLER", user.getKey());
-
-		WebSocketHelper.sendText(session, path, out);
-
-		WebSocketHelper.setSession(path, user, session, sessionId);
-	}
-
-	/**
-	 * 获取请求参数
-	 *
-	 * @author WANGWEI
-	 * @param session
-	 * @param key
-	 * @return
-	 */
-	private String getRequestParameter(Session session, String key) {
-		Map<String, List<String>> params = session.getRequestParameterMap();
-		List<String> list = params.get(key);
-
-		if (CollectionUtils.isEmpty(list)) {
-			return null;
-		}
-		String value = StringUtils.join(list, ",");
-		return value;
-	}
-
-	@OnClose
-	public void onClose(Session session, @PathParam("path") String path) {
-
-		long amount = counter.decrementAndGet();
-
-		SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
-		if (null != sessionInfo) {
-			ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
-			ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
-		} else {
-			ThreadContext.put("TRACE_ID", this.sessionId);
-		}
-
-		LOG.debug("[onClose]. path=" + path + "; sessionsAmount=" + amount);
-		WebSocketHelper.closeSession(session);
-	}
-
-	@OnMessage
-	public void onMessage(Session session, @PathParam("path") String path, String message) {
-
-		SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
-		ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
-		ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
-
-		MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
-		try {
-			JsonElement jsonEl = JsonParser.parseString(message);
-			message = JsonUtil.toJson(jsonEl);
-		} catch (JsonSyntaxException e) {
-			out.setStatus("500", "message is not a json string");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("[onMessage]. path=" + path + ". message=" + message);
-		}
-
-		SessionInfo si = WebSocketHelper.getSessionInfo(session);
-
-		User user = getRedisClient().get(si.getUser().getKey(), User.class);
-
-		if (null == user) {
-			out.setStatus("403", "no login");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		} else if (!si.getUser().getToken().equals(user.getToken())) {
-			out.setStatus("403", "token is wrong");
-			WebSocketHelper.sendText(session, path, out);
-			IOUtils.closeQuietly(session);
-			return;
-		}
-
-		Object result = null;
-		try {
-
-			Method method = MessageHandlerHolder.getMethod(path);
-			Object bean = MessageHandlerHolder.getBean(path);
-
-			Annotation[][] an2 = method.getParameterAnnotations();
-
-			boolean hasMessageParam = false;
-			int messageParamIndex = 0;
-			OUTER : for (int i = 0; i < an2.length; i++) {
-				Annotation[] an1 = an2[i];
-				for (Annotation an : an1) {
-					if (an.annotationType().equals(Message.class)) {
-						hasMessageParam = true;
-						messageParamIndex = i;
-						break OUTER;
-					}
-				}
-			}
-
-			Class<?>[] parameterTypes = method.getParameterTypes();
-			Object[] args = new Object[parameterTypes.length];
-			for (int i = 0; i < parameterTypes.length; i++) {
-				Class<?> curType = parameterTypes[i];
-				if (hasMessageParam && i == messageParamIndex) {
-					try {
-						args[i] = JsonUtil.fromJson(message, curType);
-					} catch (Exception e) {
-						throw new StatusException("500", "fail to parse message to object");
-					}
-					continue;
-				}
-				if (curType.equals(User.class)) {
-					args[i] = user;
-					continue;
-				}
-			}
-
-			result = method.invoke(bean, args);
-
-			out.setContent(result);
-
-		} catch (StatusException e) {
-			LOG.error("[onMessage-FAIL]. path=" + path + "", e);
-			out.setStatus(e.getCode(), e.getDesc());
-		} catch (Exception e) {
-			LOG.error("[onMessage-FAIL]. path=" + path + "", e);
-			out.setStatus("500", "系统异常");
-		}
-
-		WebSocketHelper.sendText(session, path, out);
-	}
-
-	@OnError
-	public void onError(Session session, @PathParam("path") String path, Throwable t) {
-
-		SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
-		if (null != sessionInfo) {
-			ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
-			ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
-		} else {
-			ThreadContext.put("TRACE_ID", this.sessionId);
-		}
-
-		LOG.error("[onError]. path=" + path, t);
-		WebSocketHelper.closeSession(session);
-	}
+    private static final Logger LOG = LoggerFactory.getLogger(WebSocketServerEndpoint.class);
+
+    private static RedisClient redisClient;
+
+    private static AtomicLong counter = new AtomicLong(0L);
+
+    private String sessionId;
+
+    private static RedisClient getRedisClient() {
+        if (null != redisClient) {
+            return redisClient;
+        }
+        redisClient = SpringContextHolder.getBean(RedisClient.class);
+        return redisClient;
+    }
+
+    @OnOpen
+    public void onOpen(Session session, @PathParam("path") String path) {
+        long amount = counter.incrementAndGet();
+
+        this.sessionId = UUID.randomUUID().toString().replace("-", "");
+
+        ThreadContext.put("TRACE_ID", sessionId);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("[onOpen]. path=" + path + "; sessionsAmount=" + amount);
+        }
+
+        MessageOut out = new MessageOut(path, sessionId);
+        out.setEventId("open");
+
+        Method method = MessageHandlerHolder.getMethod(path);
+        if (null == method) {
+            out.setStatus("404", "NOT FOUND");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+
+        String key = getRequestParameter(session, "key");
+        String token = getRequestParameter(session, "token");
+
+        if (StringUtils.isBlank(key)) {
+            LOG.error("[onOpen-FAIL]. path=" + path + ". key is blank");
+            IOUtils.closeQuietly(session);
+            return;
+        }
+        if (StringUtils.isBlank(token)) {
+            LOG.error("[onOpen-FAIL]. path=" + path + ". token is blank");
+            IOUtils.closeQuietly(session);
+            return;
+        }
+
+        User user = getRedisClient().get(key, User.class);
+
+        if (null == user) {
+            out.setStatus("403", "no login");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        } else if (!token.equals(user.getToken())) {
+            out.setStatus("403", "token is wrong");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+
+        ThreadContext.put("CALLER", user.getKey());
+
+        WebSocketHelper.sendText(session, path, out);
+
+        WebSocketHelper.setSession(path, user, session, sessionId);
+    }
+
+    /**
+     * 获取请求参数
+     *
+     * @param session
+     * @param key
+     * @return
+     * @author WANGWEI
+     */
+    private String getRequestParameter(Session session, String key) {
+        Map<String, List<String>> params = session.getRequestParameterMap();
+        List<String> list = params.get(key);
+
+        if (CollectionUtils.isEmpty(list)) {
+            return null;
+        }
+        String value = StringUtils.join(list, ",");
+        return value;
+    }
+
+    @OnClose
+    public void onClose(Session session, @PathParam("path") String path) {
+
+        long amount = counter.decrementAndGet();
+
+        SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
+        if (null != sessionInfo) {
+            ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
+            ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
+        } else {
+            ThreadContext.put("TRACE_ID", this.sessionId);
+        }
+
+        LOG.debug("[onClose]. path=" + path + "; sessionsAmount=" + amount);
+        WebSocketHelper.closeSession(session);
+    }
+
+    @OnMessage
+    public void onMessage(Session session, @PathParam("path") String path, String message) {
+
+        SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
+        ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
+        ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
+
+        MessageOut out = new MessageOut(path, sessionInfo.getSessionId());
+        try {
+            JsonElement jsonEl = JsonParser.parseString(message);
+            message = JsonUtil.toJson(jsonEl);
+        } catch (JsonSyntaxException e) {
+            out.setStatus("500", "message is not a json string");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("[onMessage]. path=" + path + ". message=" + message);
+        }
+
+        SessionInfo si = WebSocketHelper.getSessionInfo(session);
+
+        User user = getRedisClient().get(si.getUser().getKey(), User.class);
+
+        if (null == user) {
+            out.setStatus("403", "no login");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        } else if (!si.getUser().getToken().equals(user.getToken())) {
+            out.setStatus("403", "token is wrong");
+            WebSocketHelper.sendText(session, path, out);
+            IOUtils.closeQuietly(session);
+            return;
+        }
+
+        Object result = null;
+        try {
+
+            Method method = MessageHandlerHolder.getMethod(path);
+            Object bean = MessageHandlerHolder.getBean(path);
+
+            Annotation[][] an2 = method.getParameterAnnotations();
+
+            boolean hasMessageParam = false;
+            int messageParamIndex = 0;
+            OUTER:
+            for (int i = 0; i < an2.length; i++) {
+                Annotation[] an1 = an2[i];
+                for (Annotation an : an1) {
+                    if (an.annotationType().equals(Message.class)) {
+                        hasMessageParam = true;
+                        messageParamIndex = i;
+                        break OUTER;
+                    }
+                }
+            }
+
+            Class<?>[] parameterTypes = method.getParameterTypes();
+            Object[] args = new Object[parameterTypes.length];
+            for (int i = 0; i < parameterTypes.length; i++) {
+                Class<?> curType = parameterTypes[i];
+                if (hasMessageParam && i == messageParamIndex) {
+                    try {
+                        args[i] = JsonUtil.fromJson(message, curType);
+                    } catch (Exception e) {
+                        throw new StatusException("500", "fail to parse message to object");
+                    }
+                    continue;
+                }
+                if (curType.equals(User.class)) {
+                    args[i] = user;
+                    continue;
+                }
+            }
+
+            result = method.invoke(bean, args);
+
+            out.setContent(result);
+
+        } catch (StatusException e) {
+            LOG.error("[onMessage-FAIL]. path=" + path + "", e);
+            out.setStatus(e.getCode(), e.getDesc());
+        } catch (Exception e) {
+            LOG.error("[onMessage-FAIL]. path=" + path + "", e);
+            out.setStatus("500", "系统异常");
+        }
+
+        WebSocketHelper.sendText(session, path, out);
+    }
+
+    @OnError
+    public void onError(Session session, @PathParam("path") String path, Throwable t) {
+
+        SessionInfo sessionInfo = WebSocketHelper.getSessionInfo(session);
+        if (null != sessionInfo) {
+            ThreadContext.put("TRACE_ID", sessionInfo.getSessionId());
+            ThreadContext.put("CALLER", sessionInfo.getUser().getKey());
+        } else {
+            ThreadContext.put("TRACE_ID", this.sessionId);
+        }
+
+        LOG.error("[onError]. path=" + path, t);
+        WebSocketHelper.closeSession(session);
+    }
 
 }