sunkean пре 2 година
родитељ
комит
09f10bf5b9

+ 10 - 0
src/main/java/com/izouma/meta/config/Constants.java

@@ -45,6 +45,16 @@ public interface Constants {
 
     String REDIS_PREFIX = "meta:";
 
+    String META_ROBOT_NICK_NAME = "metaRobot";
+
+    String META_ROBOT_USER_ID = "7970191";
+
+    String META_ROBOT_MESSAGE_BODY = "{type:9,objectId:%S}";
+
+    long META_ROBOT_SEND_MSG_DELAY_MS = 0;
+
+    long META_ROBOT_SEND_MSG_PERIOD_MS = 200;
+
     interface MetaRestCode {
 
         int success = 200;

+ 2 - 0
src/main/java/com/izouma/meta/repo/MetaObjectMoveRepo.java

@@ -8,4 +8,6 @@ import java.util.List;
 
 public interface MetaObjectMoveRepo extends JpaRepository<MetaObjectMove, Long>, JpaSpecificationExecutor<MetaObjectMove> {
     List<MetaObjectMove> findAllByDelAndRun(boolean del, boolean run);
+
+    MetaObjectMove findByObjectIdAndDel(Long objectId, boolean del);
 }

+ 3 - 8
src/main/java/com/izouma/meta/web/MMOWebSocketController.java

@@ -1,5 +1,6 @@
 package com.izouma.meta.web;
 
+import com.izouma.meta.config.Constants;
 import com.izouma.meta.websocket.MMOWebSocket;
 import lombok.AllArgsConstructor;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -15,12 +16,6 @@ import java.util.concurrent.*;
 @AllArgsConstructor
 public class MMOWebSocketController {
 
-    private static final String NICK_NAME    = "metaRobot";
-    private static final String USER_ID      = "7970191";
-    private static final String MESSAGE_BODY = "{type:9,objectId:%S}";
-    private static final long   DELAY_MS     = 0;
-    private static final long   PERIOD_MS    = 200;
-
     private MMOWebSocket mmoWebSocket;
 
     private final Map<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();
@@ -31,7 +26,7 @@ public class MMOWebSocketController {
             throw new IllegalArgumentException(String.format("Task with id %S is already running", objectId));
         }
         ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
-        ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> sendMessage(objectId), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS);
+        ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> sendMessage(objectId), Constants.META_ROBOT_SEND_MSG_DELAY_MS, Constants.META_ROBOT_SEND_MSG_PERIOD_MS, TimeUnit.MILLISECONDS);
         tasks.put(objectId, future);
     }
 
@@ -46,7 +41,7 @@ public class MMOWebSocketController {
 
     private void sendMessage(String objectId) {
         if (mmoWebSocket != null) {
-            mmoWebSocket.onMessage(NICK_NAME, USER_ID, String.format(MESSAGE_BODY, objectId), null);
+            mmoWebSocket.onMessage(Constants.META_ROBOT_NICK_NAME, Constants.META_ROBOT_USER_ID, String.format(Constants.META_ROBOT_MESSAGE_BODY, objectId), null);
         }
     }
 }

+ 51 - 36
src/main/java/com/izouma/meta/websocket/MMOWebSocket.java

@@ -67,7 +67,7 @@ public class MMOWebSocket {
         init();
         // 判断当前玩家是否在其他地方登陆
         if (clients.containsKey(Constants.REDIS_PREFIX.concat(userId))) {
-            log.info(String.format("当前玩家[%S]已经在别处登陆,sessionId为[%S]", userId, session.getId()));
+            log.info(String.format("当前玩家: %s 已经在别处登陆, sessionId为: %s", userId, session.getId()));
             // 关闭连接
             MMOSingleMessage mmoSingleMessage = new MMOSingleMessage();
             mmoSingleMessage.setMessageType(6);
@@ -94,14 +94,14 @@ public class MMOWebSocket {
         MMOMessage mmoMessage = new MMOMessage();
         mmoMessage.setMessageType(5);
         mmoMessage.setMessage(save);
-        log.info(String.format("通知玩家[%S],本次登陆信息[%S]", userId, JSON.toJSONString(mmoMessage)));
+        log.info(String.format("通知玩家: %s, 本次登陆信息: %s", userId, JSON.toJSONString(mmoMessage)));
         websocketCommon.sendMessageTo(clients, JSON.toJSONString(mmoMessage), Constants.REDIS_PREFIX.concat(userId));
     }
 
     @OnError
     public void onError(Session session, Throwable error) {
         // 异常处理
-        log.error(String.format("sessionId[%S]的服务端发生了错误:[%S]", session.getId(), error.getMessage()));
+        log.error(String.format("sessionId: %s 的服务端发生了错误, 错误信息为: %s", session.getId(), error.getMessage()));
     }
 
     @OnClose
@@ -126,7 +126,7 @@ public class MMOWebSocket {
         }
         MetaMMOLoginInfo dbMetaMMOLoginInfo = metaMMOLoginInfoRepo.findById(metaMMOLoginInfo.getId()).orElse(null);
         if (Objects.isNull(dbMetaMMOLoginInfo)) {
-            log.error(String.format("数据库中不存在id[%S]的记录", metaMMOLoginInfo.getId()));
+            log.error(String.format("数据库中不存在id: %s 的记录", metaMMOLoginInfo.getId()));
             return;
         }
         ObjUtils.merge(dbMetaMMOLoginInfo, metaMMOLoginInfo);
@@ -147,7 +147,7 @@ public class MMOWebSocket {
             return;
         }
         if (Constants.HEART_RECEIVE.equals(message)) {
-            log.info(String.format("sessionId:[%S] userId:[%S] 连接正常", session.getId(), userId));
+            log.info(String.format("sessionId: %s , userId: %s 连接正常", session.getId(), userId));
             websocketCommon.sendMessageTo(clients, Constants.HEART_RETURN, Constants.REDIS_PREFIX.concat(userId));
             return;
         }
@@ -158,34 +158,46 @@ public class MMOWebSocket {
             return;
         }
         int type = Integer.parseInt(jsonObject.getString("type"));
+        // type = 9 广播物体坐标信息
         if (type == 9) {
-            List<MetaObjectMove> metaObjectMoves = metaObjectMoveRepo.findAllByDelAndRun(false, true);
-            if (CollectionUtils.isEmpty(metaObjectMoves)) {
+            log.info(String.format("来自客户端消息: %s", message));
+            Long objectId;
+            try {
+                objectId = Long.parseLong(jsonObject.getString("objectId"));
+            } catch (Exception e) {
+                log.error(String.format("objectId parse to long throw exception: %s", e.getMessage()));
                 return;
             }
-            for (MetaObjectMove metaObjectMove : metaObjectMoves) {
-                String cityId = String.valueOf(metaObjectMove.getCityId());
-                String regionId = String.valueOf(metaObjectMove.getRegionId());
-                String key = cityId.concat(":").concat(regionId);
-                List<String> otherUserIds = remove(key, userId);
-                MetaObjectMoveCoordinate metaObjectMoveCoordinate = null;
-                try {
-                    String str = websocketCommon.getRequest("/metaObjectMove/".concat(String.valueOf(metaObjectMove.getObjectId())).concat("/queryCoordinate"));
-                    metaObjectMoveCoordinate = JSONObject.parseObject(str, MetaObjectMoveCoordinate.class);
-                } catch (Exception e) {
-                    String errMsg = String.format("MetaObjectMoveCoordinate JSON parse throw exception:[%S]", e);
-                    log.error(errMsg);
-                }
-                if (Objects.isNull(metaObjectMoveCoordinate)) {
-                    log.error(String.format("物体[%S]坐标不存在", metaObjectMove.getObjectId()));
-                    return;
-                }
-                buildMessageForSendingToAllOther(otherUserIds, 9, metaObjectMoveCoordinate);
+            MetaObjectMove metaObjectMove = metaObjectMoveRepo.findByObjectIdAndDel(objectId, false);
+            if (Objects.isNull(metaObjectMove)) {
+                log.error(String.format("物体: %s 不存在", objectId));
+                return;
+            }
+            if (!metaObjectMove.isRun()) {
+                log.error(String.format("物体: %s 已经停运", objectId));
+                return;
+            }
+            String cityId = String.valueOf(metaObjectMove.getCityId());
+            String regionId = String.valueOf(metaObjectMove.getRegionId());
+            String key = cityId.concat(":").concat(regionId);
+            List<String> otherUserIds = remove(key, userId);
+            MetaObjectMoveCoordinate metaObjectMoveCoordinate;
+            try {
+                String str = websocketCommon.getRequest("/metaObjectMove/".concat(String.valueOf(metaObjectMove.getObjectId())).concat("/queryCoordinate"));
+                metaObjectMoveCoordinate = JSONObject.parseObject(str, MetaObjectMoveCoordinate.class);
+            } catch (Exception e) {
+                String errMsg = String.format("MetaObjectMoveCoordinate JSON parse throw exception: %s", e);
+                log.error(errMsg);
                 return;
             }
-            ;
+            if (Objects.isNull(metaObjectMoveCoordinate)) {
+                log.error(String.format("物体: %s 坐标信息不存在", metaObjectMove.getObjectId()));
+                return;
+            }
+            buildMessageForSendingToAllOther(otherUserIds, 9, metaObjectMoveCoordinate);
+            return;
         }
-        log.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
+        log.info(String.format("来自客户端消息:%s 客户端的id是:%s", message, session.getId()));
         String cityId = jsonObject.getString("cityId");
         String regionId = jsonObject.getString("regionId");
         String key = cityId.concat(":").concat(regionId);
@@ -194,7 +206,7 @@ public class MMOWebSocket {
         List<MetaMMOLoginInfo> metaMMOLoginInfos = redisTemplate.opsForValue().multiGet(otherUserIds);
         switch (type) {
             case 1:
-                log.info("当前操作类型为1 -> 玩家进入地图");
+                log.info(String.format("当前操作类型为: %s -> 玩家进入地图", type));
                 metaMMOLoginInfo = buildMetaMMOLoginInfo(jsonObject, Long.parseLong(cityId), Long.parseLong(regionId), nickName, userId);
                 if (CollectionUtils.isNotEmpty(otherUserIds)) {
                     if (CollectionUtils.isNotEmpty(metaMMOLoginInfos)) {
@@ -209,7 +221,7 @@ public class MMOWebSocket {
                 redisTemplate.opsForList().leftPush(Constants.REDIS_PREFIX.concat(key), Constants.REDIS_PREFIX.concat(userId));
                 break;
             case 2:
-                log.info(String.format("当前操作类型为[%S] -> 玩家切换区域", type));
+                log.info(String.format("当前操作类型为: %s -> 玩家切换区域", type));
                 metaMMOLoginInfo = buildMetaMMOLoginInfo(jsonObject, Long.parseLong(cityId), Long.parseLong(regionId), nickName, userId);
                 if (CollectionUtils.isNotEmpty(otherUserIds)) {
                     // 分发自己信息给区域内其他玩家
@@ -237,7 +249,7 @@ public class MMOWebSocket {
                 redisTemplate.opsForList().leftPush(Constants.REDIS_PREFIX.concat(key), Constants.REDIS_PREFIX.concat(userId));
                 break;
             case 3:
-                log.info(String.format("当前操作类型为[%S] -> 玩家在地图内移动", type));
+                log.info(String.format("当前操作类型为: %s -> 玩家在地图内移动", type));
                 metaMMOLoginInfo = (MetaMMOLoginInfo) redisTemplate.opsForValue().get(Constants.REDIS_PREFIX.concat(userId));
                 if (Objects.isNull(metaMMOLoginInfo)) {
                     log.error("缓存中不存在本玩家信息");
@@ -250,7 +262,7 @@ public class MMOWebSocket {
                 redisTemplate.opsForValue().set(Constants.REDIS_PREFIX.concat(userId), metaMMOLoginInfo);
                 break;
             case 4:
-                log.info(String.format("当前操作类型为[%S] -> 玩家进入大厅", type));
+                log.info(String.format("当前操作类型为: %s -> 玩家进入大厅", type));
                 metaMMOLoginInfo = (MetaMMOLoginInfo) redisTemplate.opsForValue().get(Constants.REDIS_PREFIX.concat(userId));
                 if (Objects.isNull(metaMMOLoginInfo)) {
                     log.error("缓存中不存在本玩家信息");
@@ -261,7 +273,7 @@ public class MMOWebSocket {
                 // 更新库中玩家位置信息
                 MetaMMOLoginInfo dbMetaMMOLoginInfo = metaMMOLoginInfoRepo.findById(metaMMOLoginInfo.getId()).orElse(null);
                 if (Objects.isNull(dbMetaMMOLoginInfo)) {
-                    log.error(String.format("数据库不存在id[%S]的记录", metaMMOLoginInfo.getId()));
+                    log.error(String.format("数据库不存在id: %s 的记录", metaMMOLoginInfo.getId()));
                     break;
                 }
                 dbMetaMMOLoginInfo.setAxisX(metaMMOLoginInfo.getAxisX());
@@ -286,7 +298,7 @@ public class MMOWebSocket {
                 metaMMOLoginInfoRepo.save(dbMetaMMOLoginInfo);
                 break;
             default:
-                log.error(String.format("不存在的操作类型[%S]", type));
+                log.error(String.format("不存在的操作类型: %s", type));
         }
 
     }
@@ -312,10 +324,10 @@ public class MMOWebSocket {
         }
         userIds.forEach(id -> {
             try {
-                log.info(String.format("服务器给所有当前区域内在线用户发送消息,当前在线人员为[%S]。消息:[%S]", id, JSON.toJSONString(mmoMessage)));
+                log.info(String.format("服务器给所有当前区域内在线用户发送消息, 当前在线人员为: %s, 消息内容: %s", id, JSON.toJSONString(mmoMessage)));
                 clients.get(id).getBasicRemote().sendText(JSON.toJSONString(mmoMessage));
             } catch (Exception e) {
-                log.error(String.format("send message [%S] to [%S] throw exception [%S]:", JSON.toJSONString(mmoMessage), id, e));
+                log.error(String.format("send message %s to %s throw exception %s:", JSON.toJSONString(mmoMessage), id, e));
             }
         });
     }
@@ -432,6 +444,9 @@ public class MMOWebSocket {
         }
         int type = Integer.parseInt(jsonObject.getString("type"));
         if (type == 9) {
+            if (Objects.isNull(jsonObject.getString("objectId"))) {
+                return MetaServiceResult.returnError("Illegal parameter : objectId can not be null");
+            }
             return MetaServiceResult.returnSuccess("check success");
         }
         if (Objects.isNull(jsonObject.getString("cityId"))) {
@@ -459,7 +474,7 @@ public class MMOWebSocket {
     public MetaRestResult<Void> clearMMO(String userId, String regionId, String cityId) {
         init();
         if (clients.containsKey(Constants.REDIS_PREFIX.concat(userId))) {
-            String errMsg = String.format("userId[%S]用户mmo连接正常,无法清除缓存!", userId);
+            String errMsg = String.format("userId: %s 用户mmo连接正常,无法清除缓存!", userId);
             log.info(errMsg);
             return MetaRestResult.returnError(errMsg);
         }