Przeglądaj źródła

考生端接口

wangliang 5 lat temu
rodzic
commit
66774b9562

+ 2 - 2
themis-backend/src/main/java/com/qmth/themis/backend/api/TBUserController.java

@@ -152,7 +152,7 @@ public class TBUserController {
         //添加用户缓存
         redisUtil.setUser(user.getId(), user);
         //添加用户会话缓存
-        String sessionId = SessionUtil.digest(user.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), platform.getSource());
+        String sessionId = SessionUtil.digest(user.getId(), Math.abs(authDto.getRoleCodes().toString().hashCode()), platform.getSource());
 
         Date expire = SystemConstant.getExpireTime(platform);
         TBSession tbSession = new TBSession(sessionId, String.valueOf(user.getId()), authDto.getRoleCodes().toString(), platform.getSource(), platform.name(), deviceId, ServletUtil.getRequest().getLocalAddr(), token, expire);
@@ -494,7 +494,7 @@ public class TBUserController {
         //循环检查该用户下其他平台是否存在session,不存在则删除用户缓存和鉴权缓存
         boolean delete = true;
         for (Source s : Source.values()) {
-            String sessionId = SessionUtil.digest(tbUser.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), s.name());
+            String sessionId = SessionUtil.digest(tbUser.getId(), Math.abs(authDto.getRoleCodes().toString().hashCode()), s.name());
             if (Objects.nonNull(redisUtil.getUserSession(sessionId))) {
                 delete = false;
                 break;

+ 3 - 3
themis-business/src/main/java/com/qmth/themis/business/util/RedisUtil.java

@@ -211,7 +211,7 @@ public class RedisUtil {
      * @param hashKey
      * @param hashValue
      */
-    public void setMqTopicList(String key, String hashKey, Object hashValue) {
+    public void setHashList(String key, String hashKey, Object hashValue) {
         redisTemplate.opsForHash().put(key, hashKey, hashValue);
     }
 
@@ -222,7 +222,7 @@ public class RedisUtil {
      * @param hashKey
      * @return
      */
-    public Object getMqTopicList(String key, String hashKey) {
+    public Object getHashList(String key, String hashKey) {
         return redisTemplate.opsForHash().get(key, hashKey);
     }
 
@@ -232,7 +232,7 @@ public class RedisUtil {
      * @param key
      * @param hashKey
      */
-    public void deleteMqTopicList(String key, String hashKey) {
+    public void deleteHashList(String key, String hashKey) {
         redisTemplate.opsForHash().delete(key, hashKey);
     }
 

+ 2 - 2
themis-exam/src/main/java/com/qmth/themis/exam/api/TEStudentController.java

@@ -124,7 +124,7 @@ public class TEStudentController {
         //添加用户缓存
         redisUtil.setStudent(teStudent.getId(), teStudent);
         //添加用户会话缓存
-        String sessionId = SessionUtil.digest(teStudent.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), platform.getSource());
+        String sessionId = SessionUtil.digest(teStudent.getIdentity(), Math.abs(authDto.getRoleCodes().toString().hashCode()), platform.getSource());
 
         Date expire = SystemConstant.getExpireTime(platform);
         TBSession tbSession = new TBSession(sessionId, String.valueOf(teStudent.getId()), authDto.getRoleCodes().toString(), platform.getSource(), platform.name(), deviceId, ServletUtil.getRequest().getLocalAddr(), token, expire);
@@ -157,7 +157,7 @@ public class TEStudentController {
         //循环检查该用户下其他平台是否存在session,不存在则删除用户缓存和鉴权缓存
         boolean delete = true;
         for (Source s : Source.values()) {
-            String sessionId = SessionUtil.digest(teStudent.getId(), authDto.getRoleCodes().toString().replaceAll(",", "&&").replaceAll(" ", ""), s.name());
+            String sessionId = SessionUtil.digest(teStudent.getIdentity(), Math.abs(authDto.getRoleCodes().toString().hashCode()), s.name());
             if (Objects.nonNull(redisUtil.getUserSession(sessionId))) {
                 delete = false;
                 break;

+ 86 - 50
themis-exam/src/main/java/com/qmth/themis/exam/websocket/WebSocketServer.java

@@ -2,15 +2,23 @@ package com.qmth.themis.exam.websocket;//package com.qmth.themis.backend.websock
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.qmth.themis.business.entity.TBSession;
+import com.qmth.themis.business.util.RedisUtil;
+import com.qmth.themis.common.enums.ExceptionResultEnum;
+import com.qmth.themis.common.exception.BusinessException;
+import com.qmth.themis.common.signature.SignatureInfo;
+import com.qmth.themis.common.signature.SignatureType;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 
+import javax.annotation.Resource;
 import javax.websocket.*;
 import javax.websocket.server.PathParam;
 import javax.websocket.server.ServerEndpoint;
 import java.io.IOException;
+import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
 
 /**
@@ -20,7 +28,7 @@ import java.util.concurrent.ConcurrentHashMap;
  * @Author: wangliang
  * @Date: 2020/7/10
  */
-@ServerEndpoint("/oe/{platform}/{deviceId}/{Authorization}/{time}")
+@ServerEndpoint("/oe/{platform}/{deviceId}/{Authorization}/{time}/{method}")
 @Component
 public class WebSocketServer
 //        implements MessageListenerConcurrently
@@ -38,33 +46,61 @@ public class WebSocketServer
      * 与某个客户端的连接会话,需要通过它来给客户端发送数据
      */
     private Session session;
-    /**
-     * 接收userId
-     */
-    private String userId = null;
+
+    private String platform = null;
+    private String deviceId = null;
+    private String Authorization = null;
+    private Long time = null;
+    private String method = null;
+
+    @Resource
+    RedisUtil redisUtil;
 
     /**
      * 连接建立成功调用的方法
      */
     @OnOpen
-    public void onOpen(Session session, @PathParam("platform") String platform, @PathParam("deviceId") String deviceI, @PathParam("Authorization") String Authorization, @PathParam("time") Long time) {
+    public void onOpen(Session session, @PathParam("platform") String platform, @PathParam("deviceId") String deviceId, @PathParam("Authorization") String Authorization, @PathParam("time") Long time, @PathParam("method") String method) {
         this.session = session;
-        this.userId = userId;
-        if (webSocketMap.containsKey(userId)) {
-            webSocketMap.remove(userId);
-            webSocketMap.put(userId, this);
-            //加入set中
-        } else {
-            webSocketMap.put(userId, this);
-            //加入set中
-            addOnlineCount();
-            //在线数加1
+        if (Objects.isNull(platform) || Objects.equals(platform, "")) {
+            throw new BusinessException(ExceptionResultEnum.PLATFORM_INVALID);
         }
-        log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
-        try {
-            sendMessage("连接成功");
-        } catch (IOException e) {
-            log.error("用户:" + userId + ",网络异常!!!!!!");
+        if (Objects.isNull(deviceId) || Objects.equals(deviceId, "")) {
+            throw new BusinessException(ExceptionResultEnum.DEVICE_ID_INVALID);
+        }
+        this.platform = platform;
+        this.deviceId = deviceId;
+        this.Authorization = Authorization;
+        this.time = time;
+        this.method = method;
+        final SignatureInfo info = SignatureInfo
+                .parse(Authorization);
+        if (Objects.nonNull(info) && info.getType() == SignatureType.TOKEN) {
+            String sessionId = info.getInvoker();
+            TBSession tbSession = (TBSession) redisUtil.getUserSession(sessionId);
+            if (info.validate(tbSession.getAccessToken()) && info.getTimestamp() < tbSession.getExpireTime().getTime()
+                    && platform.equalsIgnoreCase(tbSession.getPlatform()) && Objects.equals(deviceId, tbSession.getDeviceId())) {
+//                if (webSocketMap.containsKey(userId)) {
+//                    webSocketMap.remove(userId);
+//                    webSocketMap.put(userId, this);
+//                    //加入set中
+//                } else {
+//                    webSocketMap.put(userId, this);
+//                    //加入set中
+//                    addOnlineCount();
+//                    //在线数加1
+//                }
+//                log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
+//                try {
+//                    sendMessage("连接成功");
+//                } catch (IOException e) {
+//                    log.error("用户:" + userId + ",网络异常!!!!!!");
+//                }
+            } else {
+                throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);
+            }
+        } else {
+            throw new BusinessException(ExceptionResultEnum.AUTHORIZATION_ERROR);
         }
     }
 
@@ -73,12 +109,12 @@ public class WebSocketServer
      */
     @OnClose
     public void onClose() {
-        if (webSocketMap.containsKey(userId)) {
-            webSocketMap.remove(userId);
-            //从set中删除
-            subOnlineCount();
-        }
-        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
+//        if (webSocketMap.containsKey(userId)) {
+//            webSocketMap.remove(userId);
+//            //从set中删除
+//            subOnlineCount();
+//        }
+//        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
     }
 
     /**
@@ -88,27 +124,27 @@ public class WebSocketServer
      */
     @OnMessage
     public void onMessage(String message, Session session) {
-        log.info("用户消息:" + userId + ",报文:" + message);
-        //可以群发消息
-        //消息保存到数据库、redis
-        if (StringUtils.isNotBlank(message)) {
-            try {
-                //解析发送的报文
-                JSONObject jsonObject = JSON.parseObject(message);
-                //追加发送人(防止串改)
-                jsonObject.put("fromUserId", this.userId);
-                String toUserId = jsonObject.getString("toUserId");
-                //传送给对应toUserId用户的websocket
-                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
-                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
-                } else {
-                    log.error("请求的userId:" + toUserId + "不在该服务器上");
-                    //否则不在这个服务器上,发送到mysql或者redis
-                }
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        }
+//        log.info("用户消息:" + userId + ",报文:" + message);
+//        //可以群发消息
+//        //消息保存到数据库、redis
+//        if (StringUtils.isNotBlank(message)) {
+//            try {
+//                //解析发送的报文
+//                JSONObject jsonObject = JSON.parseObject(message);
+//                //追加发送人(防止串改)
+//                jsonObject.put("fromUserId", this.userId);
+//                String toUserId = jsonObject.getString("toUserId");
+//                //传送给对应toUserId用户的websocket
+//                if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
+//                    webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
+//                } else {
+//                    log.error("请求的userId:" + toUserId + "不在该服务器上");
+//                    //否则不在这个服务器上,发送到mysql或者redis
+//                }
+//            } catch (Exception e) {
+//                e.printStackTrace();
+//            }
+//        }
     }
 
     /**
@@ -117,8 +153,9 @@ public class WebSocketServer
      */
     @OnError
     public void onError(Session session, Throwable error) {
-        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
+//        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
         error.printStackTrace();
+        throw new BusinessException(error.getMessage());
     }
 
     /**
@@ -128,7 +165,6 @@ public class WebSocketServer
         this.session.getBasicRemote().sendText(message);
     }
 
-
     /**
      * 发送自定义消息
      */

+ 2 - 2
themis-mq/src/main/java/com/qmth/themis/mq/listener/RocketSessionConsumer.java

@@ -74,14 +74,14 @@ public class RocketSessionConsumer implements
                 mqDto = JacksonUtil.readJson(new String(messageExt.getBody(), Constants.CHARSET), MqDto.class);
                 log.info(":{}-:{} sessionConsumer 接收到的消息:{}", threadId, threadName, JacksonUtil.parseJson(mqDto));
 //                log.info(":{}-:{} sessionConsumer mqDto sequence:{},tag:{}", threadId, threadName, mqDto.getSequence(), mqDto.getTag());
-                if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getMqTopicList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
+                if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getHashList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
                     log.info(":{}-:{} 更新db", threadId, threadName);
                     tbSessionService.saveSessionInfo(JacksonUtil.readJson(JacksonUtil.parseJson(mqDto.getBody()), TBSession.class), mqDto.getTimestamp());
                     mqDto.setAck(SystemConstant.STANDARD_ACK_TYPE);
                     TMRocketMessage tmRocketMessage = gson.fromJson(gson.toJson(mqDto), TMRocketMessage.class);
                     tmRocketMessage.setBody(JacksonUtil.parseJson(tmRocketMessage.getBody()));
                     tmRocketMessageService.saveOrUpdate(tmRocketMessage);
-                    redisUtil.deleteMqTopicList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId());
+                    redisUtil.deleteHashList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId());
                     return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                 } else {
                     log.info(":{}-:{} 消息ack未确认,重发", threadId, threadName);

+ 4 - 4
themis-mq/src/main/java/com/qmth/themis/mq/listener/RocketTaskConsumer.java

@@ -74,7 +74,7 @@ public class RocketTaskConsumer {
                     mqDto = JacksonUtil.readJson(new String(messageExt.getBody(), Constants.CHARSET), MqDto.class);
                     log.info(":{}-:{} task import Consumer接收到的消息:{}", threadId, threadName, JacksonUtil.parseJson(mqDto));
 //                    log.info(":{}-:{} task import Consumer mqDto sequence:{},tag:{}", threadId, threadName, mqDto.getSequence(), mqDto.getTag());
-                    if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getMqTopicList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
+                    if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getHashList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
                         Map<String, Object> map = (Map<String, Object>) mqDto.getBody();
                         String tag = mqDto.getTag();
                         myThreadPool.arbitratePoolTaskExecutor.execute(() -> {
@@ -94,7 +94,7 @@ public class RocketTaskConsumer {
                         mqDto.setBody(JacksonUtil.parseJson(mqDto.getBody()));
                         TMRocketMessage tmRocketMessage = gson.fromJson(gson.toJson(mqDto), TMRocketMessage.class);
                         tmRocketMessageService.saveOrUpdate(tmRocketMessage);
-                        redisUtil.deleteMqTopicList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId());
+                        redisUtil.deleteHashList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId());
                         return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                     } else {
                         log.info(":{}-:{} 消息ack未确认,重发", threadId, threadName);
@@ -172,7 +172,7 @@ public class RocketTaskConsumer {
                     mqDto = JacksonUtil.readJson(new String(messageExt.getBody(), Constants.CHARSET), MqDto.class);
                     log.info(":{}-:{} task export Consumer接收到的消息:{}", threadId, threadName, JacksonUtil.parseJson(mqDto));
 //                    log.info(":{}-:{} task ExamStudentImport Consumer mqDto sequence:{},tag:{}", threadId, threadName, mqDto.getSequence(), mqDto.getTag());
-                    if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getMqTopicList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
+                    if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(redisUtil.getHashList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId())) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
                         Map<String, Object> map = (Map<String, Object>) mqDto.getBody();
                         String tag = mqDto.getTag();
                         myThreadPool.arbitratePoolTaskExecutor.execute(() -> {
@@ -190,7 +190,7 @@ public class RocketTaskConsumer {
                         mqDto.setBody(JacksonUtil.parseJson(mqDto.getBody()));
                         TMRocketMessage tmRocketMessage = gson.fromJson(gson.toJson(mqDto), TMRocketMessage.class);
                         tmRocketMessageService.saveOrUpdate(tmRocketMessage);
-                        redisUtil.deleteMqTopicList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId());
+                        redisUtil.deleteHashList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId());
                         return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                     } else {
                         log.info(":{}-:{} 消息ack未确认,重发", threadId, threadName);

+ 3 - 3
themis-mq/src/main/java/com/qmth/themis/mq/listener/RocketUserLogConsumer.java

@@ -73,10 +73,10 @@ public class RocketUserLogConsumer implements MessageListenerConcurrently {
                 Object o = null;
                 String mqTopic = null;
                 if (tag.contains("user")) {
-                    o = redisUtil.getMqTopicList(SystemConstant.USERLOG_TOPIC_BUFFER_LIST, mqDto.getId());
+                    o = redisUtil.getHashList(SystemConstant.USERLOG_TOPIC_BUFFER_LIST, mqDto.getId());
                     mqTopic = SystemConstant.USERLOG_TOPIC_BUFFER_LIST;
                 } else if (tag.contains("student")) {
-                    o = redisUtil.getMqTopicList(SystemConstant.STUDENTLOG_TOPIC_BUFFER_LIST, mqDto.getId());
+                    o = redisUtil.getHashList(SystemConstant.STUDENTLOG_TOPIC_BUFFER_LIST, mqDto.getId());
                     mqTopic = SystemConstant.STUDENTLOG_TOPIC_BUFFER_LIST;
                 }
                 if (Objects.nonNull(mqDto.getAck()) && mqDto.getAck().intValue() != SystemConstant.STANDARD_ACK_TYPE && Objects.nonNull(o) && redisUtil.lock(SystemConstant.REDIS_LOCK_MQ_PREFIX, mqDto.getId(), SystemConstant.REDIS_LOCK_MQ_TIME_OUT, TimeUnit.SECONDS)) {
@@ -89,7 +89,7 @@ public class RocketUserLogConsumer implements MessageListenerConcurrently {
                     mqDto.setAck(SystemConstant.STANDARD_ACK_TYPE);
                     TMRocketMessage tmRocketMessage = gson.fromJson(gson.toJson(mqDto), TMRocketMessage.class);
                     tmRocketMessageService.saveOrUpdate(tmRocketMessage);
-                    redisUtil.deleteMqTopicList(mqTopic, mqDto.getId());
+                    redisUtil.deleteHashList(mqTopic, mqDto.getId());
                     return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                 } else {
                     log.info(":{}-:{} 消息ack未确认,重发", threadId, threadName);

+ 4 - 4
themis-mq/src/main/java/com/qmth/themis/mq/service/impl/MqDtoServiceImpl.java

@@ -93,16 +93,16 @@ public class MqDtoServiceImpl implements MqDtoService {
         if (Objects.nonNull(mqDto)) {
             switch (mqDto.getType().ordinal()) {
                 case 0:
-                    redisUtil.setMqTopicList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
+                    redisUtil.setHashList(SystemConstant.SESSION_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
                     break;
                 case 1:
-                    redisUtil.setMqTopicList(SystemConstant.STUDENTLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
+                    redisUtil.setHashList(SystemConstant.STUDENTLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
                     break;
                 case 5:
-                    redisUtil.setMqTopicList(SystemConstant.USERLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
+                    redisUtil.setHashList(SystemConstant.USERLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
                     break;
                 default:
-                    redisUtil.setMqTopicList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
+                    redisUtil.setHashList(SystemConstant.TASKLOG_TOPIC_BUFFER_LIST, mqDto.getId(), mqDto);
                     break;
             }
         }