Răsfoiți Sursa

缓存改造至redis

skyline 2 ani în urmă
părinte
comite
ccc67dc946

+ 5 - 0
entity/src/main/java/com/kym/entity/common/RedisKeys.java

@@ -9,4 +9,9 @@ public interface RedisKeys {
     String EN_PLUS_TOKEN = "EN_PLUS_TOKEN";
     String OFFLINE = "OFFLINE:";
     String OFFLINE_EXPIRED = "OFFLINE_EXPIRED:";
+    String CONNECTOR_ID_TO_SHORT_ID = "CONNECTOR_ID_TO_SHORT_ID:";
+    String CONNECTOR_ID_TO_STATION_ID = "CONNECTOR_ID_TO_STATION_ID:";
+    String STATION_ID_TO_NAME = "STATION_ID_TO_NAME:";
+    String CONNECTOR_ID_TO_PARKING_NO = "CONNECTOR_ID_TO_PARKING_NO:";
+    String ADMIN_USER_STATION_IDS = "ADMIN_USER_STATION_IDS:";
 }

+ 18 - 1
miniapp/src/main/resources/application-dev.yml

@@ -94,7 +94,7 @@ spring:
     redis:
       port: 6380
       host: 121.40.98.15
-      password: kuaiyuman
+      password: KtXA^Zx!TZmLEy(@JjB@2(TVG0kdy5)&
       database: 10
       lettuce:
         pool:
@@ -108,6 +108,23 @@ spring:
     redis:
       # 缓存过期时间:7天
       time-to-live: 604800
+  rabbitmq:
+    host: 121.40.98.15
+    port: 5674
+    username: kym
+    password: kym!@123
+    virtual-host: /
+    publisher-returns: true
+    publisher-confirms: true
+    listener:
+      simple:
+        acknowledge-mode: manual
+        retry:
+          enabled: true
+          max-attempts: 3
+          initial-interval: 3000ms
+          max-interval: 6000ms
+          multiplier: 2
 
 kym:
   notify-email: skyline@kuaiyuman.cn

+ 2 - 2
service/src/main/java/com/kym/service/admin/impl/EquipmentRelationServiceImpl.java

@@ -30,9 +30,9 @@ public class EquipmentRelationServiceImpl extends MPJBaseServiceImpl<EquipmentRe
         // 初始化KymCache shortId:equipmentId
         // 手动切换数据源
         DynamicDataSourceContextHolder.push("db-admin");
-        KymCache.INSTANCE.putShort2EquipmentId(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getShortId)));
+        KymCache.INSTANCE.putConnectorId2ShortId(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getShortId)));
         // 初始化KymCache connectorId:stationId
-        KymCache.INSTANCE.putConnector2Station(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getStationId)));
+        KymCache.INSTANCE.putConnectorId2StationId(list().stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getStationId)));
         DynamicDataSourceContextHolder.poll();
     }
 

+ 69 - 47
service/src/main/java/com/kym/service/cache/KymCache.java

@@ -1,26 +1,37 @@
 package com.kym.service.cache;
 
+import cn.hutool.extra.spring.SpringUtil;
+import com.kym.entity.admin.EquipmentRelation;
+import com.kym.entity.admin.Station;
+import com.kym.entity.common.RedisKeys;
+import com.kym.service.admin.EquipmentRelationService;
+import com.kym.service.admin.StationService;
+import org.springframework.boot.context.event.ApplicationStartedEvent;
+import org.springframework.context.ApplicationListener;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Component;
+
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
 
 /**
  * @author skyline
- * @description
+ * @description 缓存
  * @date 2023-08-25 22:58
  */
 public enum KymCache {
     INSTANCE;
 
+
     private static ConcurrentHashMap<String, String> CONNECTOR_ID_SHORT_ID_MAPPING = new ConcurrentHashMap<>();
-    private static ConcurrentHashMap<String, String> CONNECTOR_ID_STATION_ID_MAPPING = new ConcurrentHashMap<>();
-    private static ConcurrentHashMap<String, String> STATION_MAPPING = new ConcurrentHashMap<>();
-    private static ConcurrentHashMap<Long, String> ADMIN_USER_STATION = new ConcurrentHashMap<>();
     private static ConcurrentHashMap<Long, List<String>> ADMIN_USER_STATIONS = new ConcurrentHashMap<>();
-    private static ConcurrentHashMap<String, String> EQUIPMENT_ID_PARKING_NO_MAPPING = new ConcurrentHashMap<>();
 
-    public void putShort2EquipmentId(Map<String, String> map) {
+
+    public void putConnectorId2ShortId(Map<String, String> map) {
         CONNECTOR_ID_SHORT_ID_MAPPING.putAll(map);
+        map.forEach((k, v) -> KymCacheInjector.redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_SHORT_ID + k, v));
     }
 
     /**
@@ -31,20 +42,12 @@ public enum KymCache {
      */
     public String getShortIdByEquipmentIdOrConnectorId(String id) {
         var connectorId = getConnectorId(id);
-        var res = CONNECTOR_ID_SHORT_ID_MAPPING.get(connectorId);
-//        if (res == null) {
-//            var relation = relationService.lambdaQuery().eq(EquipmentRelation::getEquipmentId, equipmentId).one();
-//            if (relation != null) {
-//                res = relation.getShortId();
-//                CONNECTOR_ID_SHORT_ID_MAPPING.put(equipmentId, res);
-//            }
-//        }
-        return res;
+        return KymCacheInjector.redisTemplate.opsForValue().get(RedisKeys.CONNECTOR_ID_TO_SHORT_ID + connectorId);
     }
 
 
-    public void putConnector2Station(Map<String, String> map) {
-        CONNECTOR_ID_STATION_ID_MAPPING.putAll(map);
+    public void putConnectorId2StationId(Map<String, String> map) {
+        map.forEach((k, v) -> KymCacheInjector.redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_STATION_ID + k, v));
     }
 
     /**
@@ -55,19 +58,11 @@ public enum KymCache {
      */
     public String getStationIdByEquipmentIdOrConnectorId(String id) {
         var connectorId = getConnectorId(id);
-        var res = CONNECTOR_ID_STATION_ID_MAPPING.get(connectorId);
-//        if (res == null) {
-//            var relation = relationService.lambdaQuery().eq(EquipmentRelation::getConnectorId, connectorId).one();
-//            if (relation != null) {
-//                res = relation.getStationId();
-//                CONNECTOR_STATION_MAPPING.put(connectorId, res);
-//            }
-//        }
-        return res;
+        return KymCacheInjector.redisTemplate.opsForValue().get(RedisKeys.CONNECTOR_ID_TO_STATION_ID + connectorId);
     }
 
     public void putStationId2Name(Map<String, String> map) {
-        STATION_MAPPING.putAll(map);
+        map.forEach((k, v) -> KymCacheInjector.redisTemplate.opsForValue().set(RedisKeys.STATION_ID_TO_NAME + k, v));
     }
 
     /**
@@ -77,7 +72,7 @@ public enum KymCache {
      * @return
      */
     public String getStationNameById(String stationId) {
-        return STATION_MAPPING.get(stationId);
+        return KymCacheInjector.redisTemplate.opsForValue().get(RedisKeys.STATION_ID_TO_NAME + stationId);
     }
 
     /**
@@ -86,23 +81,13 @@ public enum KymCache {
      * @param map
      */
     public void putAdminUser2Stations(Map<Long, List<String>> map) {
-        ADMIN_USER_STATIONS.putAll(map);
+        map.forEach((k, v) -> {
+            String key = RedisKeys.ADMIN_USER_STATION_IDS + k;
+            String[] values = v.toArray(new String[0]); // 优化数组创建方式,使用varargs来避免不必要的数组拷贝
+            KymCacheInjector.redisTemplate.opsForSet().add(key, values);
+        });
     }
 
-    /**
-     * 获取运营平台操作员有权限的站点ID
-     *
-     * @param adminUserId
-     * @return
-     */
-    public String getAdminUserStationId(Long adminUserId) {
-        var res = ADMIN_USER_STATION.get(adminUserId);
-//        if (res == null) {
-//            var adminUserStation = adminUserStationService.lambdaQuery().eq(AdminUserStation::getAdminUserId, adminUserId).one();
-//            res = adminUserStation == null ? null : adminUserStation.getStationId();
-//        }
-        return res;
-    }
 
     /**
      * 获取运营平台操作员有权限的站点ID
@@ -111,11 +96,11 @@ public enum KymCache {
      * @return
      */
     public List<String> getAdminUserStationIds(Long adminUserId) {
-        return ADMIN_USER_STATIONS.get(adminUserId);
+        return KymCacheInjector.redisTemplate.opsForSet().members(RedisKeys.ADMIN_USER_STATION_IDS + adminUserId).stream().toList();
     }
 
     public void putConnectorId2ParkingNo(Map<String, String> map) {
-        EQUIPMENT_ID_PARKING_NO_MAPPING.putAll(map);
+        map.forEach((k, v) -> KymCacheInjector.redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_PARKING_NO + k, v));
     }
 
     /**
@@ -124,7 +109,7 @@ public enum KymCache {
      */
     public String getParkNoByEquipmentIdOrConnectorId(String id) {
         var connectorId = getConnectorId(id);
-        return EQUIPMENT_ID_PARKING_NO_MAPPING.get(connectorId);
+        return KymCacheInjector.redisTemplate.opsForValue().get(RedisKeys.CONNECTOR_ID_TO_PARKING_NO + connectorId);
     }
 
     /**
@@ -142,4 +127,41 @@ public enum KymCache {
             default -> null;
         };
     }
-}
+
+    @Component
+    public static class KymCacheInjector implements ApplicationListener<ApplicationStartedEvent> {
+
+        private static final StringRedisTemplate redisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
+
+        private final EquipmentRelationService equipmentRelationService;
+        private final StationService stationService;
+
+
+        private KymCacheInjector(EquipmentRelationService equipmentRelationService, StationService stationService) {
+            this.equipmentRelationService = equipmentRelationService;
+            this.stationService = stationService;
+        }
+
+        @Override
+        public void onApplicationEvent(ApplicationStartedEvent event) {
+            // 将数据库数据缓存到redis
+            var equipmentRelations = equipmentRelationService.list();
+
+            var connectorId2ShortId = equipmentRelations.stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getShortId));
+            KymCache.INSTANCE.putConnectorId2ShortId(connectorId2ShortId);
+            connectorId2ShortId.forEach((k, v) -> redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_SHORT_ID + k, v));
+
+            var connector2Station = equipmentRelations.stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getStationId));
+            KymCache.INSTANCE.putConnectorId2StationId(connector2Station);
+            connector2Station.forEach((k, v) -> redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_STATION_ID + k, v));
+
+            var stationId2Name = stationService.list().stream().collect(Collectors.toMap(Station::getStationId, Station::getStationName));
+            KymCache.INSTANCE.putStationId2Name(stationId2Name);
+            stationId2Name.forEach((k, v) -> redisTemplate.opsForValue().set(RedisKeys.STATION_ID_TO_NAME + k, v));
+
+            var connectorId2ParkingNo = equipmentRelations.stream().collect(Collectors.toMap(EquipmentRelation::getConnectorId, EquipmentRelation::getParkingNo));
+            KymCache.INSTANCE.putConnectorId2ParkingNo(connectorId2ParkingNo);
+            connectorId2ParkingNo.forEach((k, v) -> redisTemplate.opsForValue().set(RedisKeys.CONNECTOR_ID_TO_PARKING_NO + k, v));
+        }
+    }
+}

+ 2 - 2
service/src/main/java/com/kym/service/miniapp/impl/ChargeOrderServiceImpl.java

@@ -94,7 +94,7 @@ public class ChargeOrderServiceImpl extends MPJBaseServiceImpl<ChargeOrderMapper
         }
         // 判断数据权限
         if (params.getStationId() == null) {
-            params.setStationId(KymCache.INSTANCE.getAdminUserStationIds(StpUtil.getLoginIdAsLong()) == null ? null : KymCache.INSTANCE.getAdminUserStationIds(StpUtil.getLoginIdAsLong()).get(0));
+            params.setStationId(CommUtil.isEmptyOrNull(KymCache.INSTANCE.getAdminUserStationIds(StpUtil.getLoginIdAsLong())) ? null : KymCache.INSTANCE.getAdminUserStationIds(StpUtil.getLoginIdAsLong()).get(0));
         }
         PageHelper.startPage(params.getPageNum(), params.getPageSize());
         // 查询订单列表(订单编号,手机号,充电站,充电桩SN/短码,订单状态,建单时间,结算时间,充电电量,实付金额,付款状态)
@@ -233,7 +233,7 @@ public class ChargeOrderServiceImpl extends MPJBaseServiceImpl<ChargeOrderMapper
     @DS("db-admin")
     public Map<String, ?> stationStatDetail(StatQueryParam params) {
 
-        CommUtil.asserts(CommUtil.isNotEmptyAndNull(params.getStationIds()),"站点不能为空");
+        CommUtil.asserts(CommUtil.isNotEmptyAndNull(params.getStationIds()), "站点不能为空");
         if (params.getType().equals(StatQueryParam.TYPE_DAY)) {
             return stationStatDayService.lambdaQuery()
                     .in(StationStatDay::getStationId, params.getStationIds())