gaoxiong před 2 roky
rodič
revize
c814856206
24 změnil soubory, kde provedl 1252 přidání a 489 odebrání
  1. 27 0
      pom.xml
  2. 7 9
      soc-auth/src/main/java/com/xunmei/auth/service/SysLoginService.java
  3. 9 8
      soc-auth/src/main/java/com/xunmei/auth/service/SysPasswordService.java
  4. 18 2
      soc-common/soc-common-redis/pom.xml
  5. 130 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/config/RedisConfiguration.java
  6. 135 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/config/properties/RedissonProperties.java
  7. 0 49
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/configure/FastJson2JsonRedisSerializer.java
  8. 0 42
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/configure/RedisConfig.java
  9. 50 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/handler/KeyPrefixHandler.java
  10. 192 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/manager/PlusSpringCacheManager.java
  11. 0 284
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/service/RedisService.java
  12. 75 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/utils/CacheUtils.java
  13. 505 0
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/utils/RedisUtils.java
  14. 1 2
      soc-common/soc-common-redis/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  15. 10 7
      soc-common/soc-common-security/src/main/java/com/xunmei/common/security/service/TokenService.java
  16. 25 28
      soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/DictUtils.java
  17. 5 6
      soc-gateway/src/main/java/com/xunmei/gateway/filter/AuthFilter.java
  18. 8 8
      soc-gateway/src/main/java/com/xunmei/gateway/service/impl/ValidateCodeServiceImpl.java
  19. 16 9
      soc-modules/soc-modules-core/src/main/java/com/xunmei/core/resumption/controller/ResumptionController.java
  20. 2 5
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/controller/SysLogininforController.java
  21. 5 7
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/controller/SysUserOnlineController.java
  22. 18 12
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysConfigServiceImpl.java
  23. 9 3
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysDeptServiceImpl.java
  24. 5 8
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysOrgServiceImpl.java

+ 27 - 0
pom.xml

@@ -28,6 +28,8 @@
         <jjwt.version>0.9.1</jjwt.version>
         <transmittable-thread-local.version>2.14.2</transmittable-thread-local.version>
         <hutool.version>5.4.1</hutool.version>
+        <redisson.version>3.20.1</redisson.version>
+        <lock4j.version>2.2.3</lock4j.version>
         <easyexcel.version>2.2.3</easyexcel.version>
         <kaptcha.version>2.3.3</kaptcha.version>
         <dynamic-ds.version>3.5.2</dynamic-ds.version>
@@ -171,6 +173,31 @@
                 <version>${velocity.version}</version>
             </dependency>
 
+
+            <!--redisson-->
+            <dependency>
+                <groupId>org.redisson</groupId>
+                <artifactId>redisson-spring-boot-starter</artifactId>
+                <version>${redisson.version}</version>
+                <exclusions>
+                    <exclusion>
+                        <groupId>org.redisson</groupId>
+                        <artifactId>redisson-spring-data-30</artifactId>
+                    </exclusion>
+                </exclusions>
+            </dependency>
+            <dependency>
+                <groupId>org.redisson</groupId>
+                <artifactId>redisson-spring-data-27</artifactId>
+                <version>${redisson.version}</version>
+            </dependency>
+
+            <dependency>
+                <groupId>com.baomidou</groupId>
+                <artifactId>lock4j-redisson-spring-boot-starter</artifactId>
+                <version>${lock4j.version}</version>
+            </dependency>
+
             <!-- io常用工具类 -->
             <dependency>
                 <groupId>commons-io</groupId>

+ 7 - 9
soc-auth/src/main/java/com/xunmei/auth/service/SysLoginService.java

@@ -13,12 +13,11 @@ import com.xunmei.common.core.exception.ServiceException;
 import com.xunmei.common.core.text.Convert;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.utils.ip.IpUtils;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.AsymmetricEncryptionUtil;
 import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.system.api.RemoteUserService;
 import com.xunmei.system.api.domain.SysUser;
-import com.xunmei.system.api.domain.User;
 import com.xunmei.system.api.model.LoginUser;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.BoundSetOperations;
@@ -43,8 +42,7 @@ public class SysLoginService
     @Autowired
     private SysRecordLogService recordLogService;
 
-    @Autowired
-    private RedisService redisService;
+
 
     /**
      * 登录
@@ -72,7 +70,7 @@ public class SysLoginService
             throw new ServiceException("用户名不在指定范围");
         }
         // IP黑名单校验
-        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
+        String blackStr = Convert.toStr(RedisUtils.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
         if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
         {
             recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾,访问IP已被列入系统黑名单",platformType);
@@ -124,10 +122,10 @@ public class SysLoginService
             throw new RuntimeException("登录信息失效");
         }
         //如果redis中存在此key,说明已经登录过了
-        BoundSetOperations<String, Object> operations = redisService.getBoundSetOperations("loginAuth");
+       /* BoundSetOperations<String, Object> operations = redisService.getBoundSetOperations("loginAuth");
         if (Boolean.TRUE.equals(operations.isMember(decrypt))) {
             throw new RuntimeException("登录信息失效");
-        }
+        }*/
         //如果不满足此规则,说明是伪造的
         String[] split = decrypt.split(":");
         if (split.length != 2) {
@@ -142,9 +140,9 @@ public class SysLoginService
         if (System.currentTimeMillis() - Long.parseLong(timeStamp) > 300000) {
             throw new RuntimeException("登录信息失效");
         }
-        operations.add(decrypt);
+        /*operations.add(decrypt);
         operations.expireAt(DateUtil.endOfDay(new Date()));
-
+*/
 
     }
 }

+ 9 - 8
soc-auth/src/main/java/com/xunmei/auth/service/SysPasswordService.java

@@ -3,13 +3,13 @@ package com.xunmei.auth.service;
 import com.xunmei.common.core.constant.CacheConstants;
 import com.xunmei.common.core.constant.Constants;
 import com.xunmei.common.core.exception.ServiceException;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.system.api.domain.SysUser;
-import com.xunmei.system.api.domain.User;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
+import java.time.Duration;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -20,8 +20,6 @@ import java.util.concurrent.TimeUnit;
 @Component
 public class SysPasswordService
 {
-    @Autowired
-    private RedisService redisService;
 
     private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;
 
@@ -45,7 +43,8 @@ public class SysPasswordService
     {
         String username = user.getUsername();
 
-        Integer retryCount = redisService.getCacheObject(getCacheKey(username));
+        Integer retryCount =RedisUtils.getCacheObject(getCacheKey(username));
+        //Integer retryCount = redisService.getCacheObject(getCacheKey(username));
 
         if (retryCount == null)
         {
@@ -63,7 +62,8 @@ public class SysPasswordService
         {
             retryCount = retryCount + 1;
             recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, String.format("密码输入错误%s次", retryCount),platformType);
-            redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
+            RedisUtils.setCacheObject(getCacheKey(username), retryCount, Duration.ofMinutes(lockTime));
+            //redisService.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
             throw new ServiceException("用户不存在/密码错误");
         }
         else
@@ -80,9 +80,10 @@ public class SysPasswordService
 
     public void clearLoginRecordCache(String loginName)
     {
-        if (redisService.hasKey(getCacheKey(loginName)))
+        RedisUtils.deleteObject(getCacheKey(loginName));
+        /*if (redisService.hasKey(getCacheKey(loginName)))
         {
             redisService.deleteObject(getCacheKey(loginName));
-        }
+        }*/
     }
 }

+ 18 - 2
soc-common/soc-common-redis/pom.xml

@@ -19,7 +19,23 @@
         <!-- SpringBoot Boot Redis -->
         <dependency>
             <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-redis</artifactId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
+
+        <!--redisson-->
+        <dependency>
+            <groupId>org.redisson</groupId>
+            <artifactId>redisson-spring-boot-starter</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.redisson</groupId>
+            <artifactId>redisson-spring-data-27</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>lock4j-redisson-spring-boot-starter</artifactId>
         </dependency>
 
         <dependency>
@@ -29,4 +45,4 @@
         </dependency>
     </dependencies>
 
-</project>
+</project>

+ 130 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/config/RedisConfiguration.java

@@ -0,0 +1,130 @@
+package com.xunmei.common.redis.config;
+
+import cn.hutool.core.util.ObjectUtil;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.xunmei.common.redis.config.properties.RedissonProperties;
+import com.xunmei.common.redis.handler.KeyPrefixHandler;
+import com.xunmei.common.redis.manager.PlusSpringCacheManager;
+import lombok.extern.slf4j.Slf4j;
+import org.redisson.codec.JsonJacksonCodec;
+import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Bean;
+
+/**
+ * redis配置
+ *
+ * @author xunmei
+ */
+@Slf4j
+@AutoConfiguration
+@EnableCaching
+@EnableConfigurationProperties(RedissonProperties.class)
+public class RedisConfiguration {
+
+    @Autowired
+    private RedissonProperties redissonProperties;
+
+    @Autowired
+    private ObjectMapper objectMapper;
+
+    @Bean
+    public RedissonAutoConfigurationCustomizer redissonCustomizer() {
+        return config -> {
+            config.setThreads(redissonProperties.getThreads())
+                .setNettyThreads(redissonProperties.getNettyThreads())
+                .setCodec(new JsonJacksonCodec(objectMapper));
+            RedissonProperties.SingleServerConfig singleServerConfig = redissonProperties.getSingleServerConfig();
+            if (ObjectUtil.isNotNull(singleServerConfig)) {
+                // 使用单机模式
+                config.useSingleServer()
+                    //设置redis key前缀
+                    .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix()))
+                    .setTimeout(singleServerConfig.getTimeout())
+                    .setClientName(singleServerConfig.getClientName())
+                    .setIdleConnectionTimeout(singleServerConfig.getIdleConnectionTimeout())
+                    .setSubscriptionConnectionPoolSize(singleServerConfig.getSubscriptionConnectionPoolSize())
+                    .setConnectionMinimumIdleSize(singleServerConfig.getConnectionMinimumIdleSize())
+                    .setConnectionPoolSize(singleServerConfig.getConnectionPoolSize());
+            }
+            // 集群配置方式 参考下方注释
+            RedissonProperties.ClusterServersConfig clusterServersConfig = redissonProperties.getClusterServersConfig();
+            if (ObjectUtil.isNotNull(clusterServersConfig)) {
+                config.useClusterServers()
+                    //设置redis key前缀
+                    .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix()))
+                    .setTimeout(clusterServersConfig.getTimeout())
+                    .setClientName(clusterServersConfig.getClientName())
+                    .setIdleConnectionTimeout(clusterServersConfig.getIdleConnectionTimeout())
+                    .setSubscriptionConnectionPoolSize(clusterServersConfig.getSubscriptionConnectionPoolSize())
+                    .setMasterConnectionMinimumIdleSize(clusterServersConfig.getMasterConnectionMinimumIdleSize())
+                    .setMasterConnectionPoolSize(clusterServersConfig.getMasterConnectionPoolSize())
+                    .setSlaveConnectionMinimumIdleSize(clusterServersConfig.getSlaveConnectionMinimumIdleSize())
+                    .setSlaveConnectionPoolSize(clusterServersConfig.getSlaveConnectionPoolSize())
+                    .setReadMode(clusterServersConfig.getReadMode())
+                    .setSubscriptionMode(clusterServersConfig.getSubscriptionMode());
+            }
+            log.info("初始化 redis 配置");
+        };
+    }
+
+    /**
+     * 自定义缓存管理器 整合spring-cache
+     */
+    @Bean
+    public CacheManager cacheManager() {
+        return new PlusSpringCacheManager();
+    }
+
+    /**
+     * redis集群配置 yml
+     *
+     * --- # redis 集群配置(单机与集群只能开启一个另一个需要注释掉)
+     * spring:
+     *   redis:
+     *     cluster:
+     *       nodes:
+     *         - 192.168.0.100:6379
+     *         - 192.168.0.101:6379
+     *         - 192.168.0.102:6379
+     *     # 密码
+     *     password:
+     *     # 连接超时时间
+     *     timeout: 10s
+     *     # 是否开启ssl
+     *     ssl: false
+     *
+     * redisson:
+     *   # 线程池数量
+     *   threads: 16
+     *   # Netty线程池数量
+     *   nettyThreads: 32
+     *   # 集群配置
+     *   clusterServersConfig:
+     *     # 客户端名称
+     *     clientName: ${xunmei.name}
+     *     # master最小空闲连接数
+     *     masterConnectionMinimumIdleSize: 32
+     *     # master连接池大小
+     *     masterConnectionPoolSize: 64
+     *     # slave最小空闲连接数
+     *     slaveConnectionMinimumIdleSize: 32
+     *     # slave连接池大小
+     *     slaveConnectionPoolSize: 64
+     *     # 连接空闲超时,单位:毫秒
+     *     idleConnectionTimeout: 10000
+     *     # 命令等待超时,单位:毫秒
+     *     timeout: 3000
+     *     # 发布和订阅连接池大小
+     *     subscriptionConnectionPoolSize: 50
+     *     # 读取模式
+     *     readMode: "SLAVE"
+     *     # 订阅模式
+     *     subscriptionMode: "MASTER"
+     */
+
+}

+ 135 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/config/properties/RedissonProperties.java

@@ -0,0 +1,135 @@
+package com.xunmei.common.redis.config.properties;
+
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import org.redisson.config.ReadMode;
+import org.redisson.config.SubscriptionMode;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * Redisson 配置属性
+ *
+ * @author xunmei
+ */
+@Data
+@ConfigurationProperties(prefix = "redisson")
+public class RedissonProperties {
+
+    /**
+     * redis缓存key前缀
+     */
+    private String keyPrefix;
+
+    /**
+     * 线程池数量,默认值 = 当前处理核数量 * 2
+     */
+    private int threads;
+
+    /**
+     * Netty线程池数量,默认值 = 当前处理核数量 * 2
+     */
+    private int nettyThreads;
+
+    /**
+     * 单机服务配置
+     */
+    private SingleServerConfig singleServerConfig;
+
+    /**
+     * 集群服务配置
+     */
+    private ClusterServersConfig clusterServersConfig;
+
+    @Data
+    @NoArgsConstructor
+    public static class SingleServerConfig {
+
+        /**
+         * 客户端名称
+         */
+        private String clientName;
+
+        /**
+         * 最小空闲连接数
+         */
+        private int connectionMinimumIdleSize;
+
+        /**
+         * 连接池大小
+         */
+        private int connectionPoolSize;
+
+        /**
+         * 连接空闲超时,单位:毫秒
+         */
+        private int idleConnectionTimeout;
+
+        /**
+         * 命令等待超时,单位:毫秒
+         */
+        private int timeout;
+
+        /**
+         * 发布和订阅连接池大小
+         */
+        private int subscriptionConnectionPoolSize;
+
+    }
+
+    @Data
+    @NoArgsConstructor
+    public static class ClusterServersConfig {
+
+        /**
+         * 客户端名称
+         */
+        private String clientName;
+
+        /**
+         * master最小空闲连接数
+         */
+        private int masterConnectionMinimumIdleSize;
+
+        /**
+         * master连接池大小
+         */
+        private int masterConnectionPoolSize;
+
+        /**
+         * slave最小空闲连接数
+         */
+        private int slaveConnectionMinimumIdleSize;
+
+        /**
+         * slave连接池大小
+         */
+        private int slaveConnectionPoolSize;
+
+        /**
+         * 连接空闲超时,单位:毫秒
+         */
+        private int idleConnectionTimeout;
+
+        /**
+         * 命令等待超时,单位:毫秒
+         */
+        private int timeout;
+
+        /**
+         * 发布和订阅连接池大小
+         */
+        private int subscriptionConnectionPoolSize;
+
+        /**
+         * 读取模式
+         */
+        private ReadMode readMode;
+
+        /**
+         * 订阅模式
+         */
+        private SubscriptionMode subscriptionMode;
+
+    }
+
+}

+ 0 - 49
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/configure/FastJson2JsonRedisSerializer.java

@@ -1,49 +0,0 @@
-package com.xunmei.common.redis.configure;
-
-import com.alibaba.fastjson2.JSON;
-import com.alibaba.fastjson2.JSONReader;
-import com.alibaba.fastjson2.JSONWriter;
-import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.data.redis.serializer.SerializationException;
-
-import java.nio.charset.Charset;
-
-/**
- * Redis使用FastJson序列化
- *
- */
-public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
-{
-    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
-
-    private Class<T> clazz;
-
-
-    public FastJson2JsonRedisSerializer(Class<T> clazz)
-    {
-        super();
-        this.clazz = clazz;
-    }
-
-    @Override
-    public byte[] serialize(T t) throws SerializationException
-    {
-        if (t == null)
-        {
-            return new byte[0];
-        }
-        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
-    }
-
-    @Override
-    public T deserialize(byte[] bytes) throws SerializationException
-    {
-        if (bytes == null || bytes.length <= 0)
-        {
-            return null;
-        }
-        String str = new String(bytes, DEFAULT_CHARSET);
-
-        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
-    }
-}

+ 0 - 42
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/configure/RedisConfig.java

@@ -1,42 +0,0 @@
-package com.xunmei.common.redis.configure;
-
-import org.springframework.boot.autoconfigure.AutoConfigureBefore;
-import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
-import org.springframework.cache.annotation.CachingConfigurerSupport;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-/**
- * redis配置
- *
- */
-@Configuration
-@EnableCaching
-@AutoConfigureBefore(RedisAutoConfiguration.class)
-public class RedisConfig extends CachingConfigurerSupport
-{
-    @Bean
-    @SuppressWarnings(value = { "unchecked", "rawtypes" })
-    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
-    {
-        RedisTemplate<Object, Object> template = new RedisTemplate<>();
-        template.setConnectionFactory(connectionFactory);
-
-        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
-
-        // 使用StringRedisSerializer来序列化和反序列化redis的key值
-        template.setKeySerializer(new StringRedisSerializer());
-        template.setValueSerializer(serializer);
-
-        // Hash的key也采用StringRedisSerializer的序列化方式
-        template.setHashKeySerializer(new StringRedisSerializer());
-        template.setHashValueSerializer(serializer);
-
-        template.afterPropertiesSet();
-        return template;
-    }
-}

+ 50 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/handler/KeyPrefixHandler.java

@@ -0,0 +1,50 @@
+package com.xunmei.common.redis.handler;
+
+import com.xunmei.common.core.utils.StringUtils;
+import org.redisson.api.NameMapper;
+
+/**
+ * redis缓存key前缀处理
+ *
+ * @author ye
+ * @date 2022/7/14 17:44
+ * @since 4.3.0
+ */
+public class KeyPrefixHandler implements NameMapper {
+
+    private final String keyPrefix;
+
+    public KeyPrefixHandler(String keyPrefix) {
+        //前缀为空 则返回空前缀
+        this.keyPrefix = StringUtils.isBlank(keyPrefix) ? "" : keyPrefix + ":";
+    }
+
+    /**
+     * 增加前缀
+     */
+    @Override
+    public String map(String name) {
+        if (StringUtils.isBlank(name)) {
+            return null;
+        }
+        if (StringUtils.isNotBlank(keyPrefix) && !name.startsWith(keyPrefix)) {
+            return keyPrefix + name;
+        }
+        return name;
+    }
+
+    /**
+     * 去除前缀
+     */
+    @Override
+    public String unmap(String name) {
+        if (StringUtils.isBlank(name)) {
+            return null;
+        }
+        if (StringUtils.isNotBlank(keyPrefix) && name.startsWith(keyPrefix)) {
+            return name.substring(keyPrefix.length());
+        }
+        return name;
+    }
+
+}

+ 192 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/manager/PlusSpringCacheManager.java

@@ -0,0 +1,192 @@
+/**
+ * Copyright (c) 2013-2021 Nikita Koksharov
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.xunmei.common.redis.manager;
+
+import com.xunmei.common.redis.utils.RedisUtils;
+import org.redisson.api.RMap;
+import org.redisson.api.RMapCache;
+import org.redisson.spring.cache.CacheConfig;
+import org.redisson.spring.cache.RedissonCache;
+import org.springframework.boot.convert.DurationStyle;
+import org.springframework.cache.Cache;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.transaction.TransactionAwareCacheDecorator;
+import org.springframework.util.StringUtils;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * A {@link CacheManager} implementation
+ * backed by Redisson instance.
+ * <p>
+ * 修改 RedissonSpringCacheManager 源码
+ * 重写 cacheName 处理方法 支持多参数
+ *
+ * @author Nikita Koksharov
+ *
+ */
+@SuppressWarnings("unchecked")
+public class PlusSpringCacheManager implements CacheManager {
+
+    private boolean dynamic = true;
+
+    private boolean allowNullValues = true;
+
+    private boolean transactionAware = true;
+
+    Map<String, CacheConfig> configMap = new ConcurrentHashMap<>();
+    ConcurrentMap<String, Cache> instanceMap = new ConcurrentHashMap<>();
+
+    /**
+     * Creates CacheManager supplied by Redisson instance
+     */
+    public PlusSpringCacheManager() {
+    }
+
+
+    /**
+     * Defines possibility of storing {@code null} values.
+     * <p>
+     * Default is <code>true</code>
+     *
+     * @param allowNullValues stores if <code>true</code>
+     */
+    public void setAllowNullValues(boolean allowNullValues) {
+        this.allowNullValues = allowNullValues;
+    }
+
+    /**
+     * Defines if cache aware of Spring-managed transactions.
+     * If {@code true} put/evict operations are executed only for successful transaction in after-commit phase.
+     * <p>
+     * Default is <code>false</code>
+     *
+     * @param transactionAware cache is transaction aware if <code>true</code>
+     */
+    public void setTransactionAware(boolean transactionAware) {
+        this.transactionAware = transactionAware;
+    }
+
+    /**
+     * Defines 'fixed' cache names.
+     * A new cache instance will not be created in dynamic for non-defined names.
+     * <p>
+     * `null` parameter setups dynamic mode
+     *
+     * @param names of caches
+     */
+    public void setCacheNames(Collection<String> names) {
+        if (names != null) {
+            for (String name : names) {
+                getCache(name);
+            }
+            dynamic = false;
+        } else {
+            dynamic = true;
+        }
+    }
+
+    /**
+     * Set cache config mapped by cache name
+     *
+     * @param config object
+     */
+    public void setConfig(Map<String, ? extends CacheConfig> config) {
+        this.configMap = (Map<String, CacheConfig>) config;
+    }
+
+    protected CacheConfig createDefaultConfig() {
+        return new CacheConfig();
+    }
+
+    @Override
+    public Cache getCache(String name) {
+        // 重写 cacheName 支持多参数
+        String[] array = StringUtils.delimitedListToStringArray(name, "#");
+        name = array[0];
+
+        Cache cache = instanceMap.get(name);
+        if (cache != null) {
+            return cache;
+        }
+        if (!dynamic) {
+            return cache;
+        }
+
+        CacheConfig config = configMap.get(name);
+        if (config == null) {
+            config = createDefaultConfig();
+            configMap.put(name, config);
+        }
+
+        if (array.length > 1) {
+            config.setTTL(DurationStyle.detectAndParse(array[1]).toMillis());
+        }
+        if (array.length > 2) {
+            config.setMaxIdleTime(DurationStyle.detectAndParse(array[2]).toMillis());
+        }
+        if (array.length > 3) {
+            config.setMaxSize(Integer.parseInt(array[3]));
+        }
+
+        if (config.getMaxIdleTime() == 0 && config.getTTL() == 0 && config.getMaxSize() == 0) {
+            return createMap(name, config);
+        }
+
+        return createMapCache(name, config);
+    }
+
+    private Cache createMap(String name, CacheConfig config) {
+        RMap<Object, Object> map = RedisUtils.getClient().getMap(name);
+
+        Cache cache = new RedissonCache(map, allowNullValues);
+        if (transactionAware) {
+            cache = new TransactionAwareCacheDecorator(cache);
+        }
+        Cache oldCache = instanceMap.putIfAbsent(name, cache);
+        if (oldCache != null) {
+            cache = oldCache;
+        }
+        return cache;
+    }
+
+    private Cache createMapCache(String name, CacheConfig config) {
+        RMapCache<Object, Object> map = RedisUtils.getClient().getMapCache(name);
+
+        Cache cache = new RedissonCache(map, config, allowNullValues);
+        if (transactionAware) {
+            cache = new TransactionAwareCacheDecorator(cache);
+        }
+        Cache oldCache = instanceMap.putIfAbsent(name, cache);
+        if (oldCache != null) {
+            cache = oldCache;
+        } else {
+            map.setMaxSize(config.getMaxSize());
+        }
+        return cache;
+    }
+
+    @Override
+    public Collection<String> getCacheNames() {
+        return Collections.unmodifiableSet(configMap.keySet());
+    }
+
+
+}

+ 0 - 284
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/service/RedisService.java

@@ -1,284 +0,0 @@
-package com.xunmei.common.redis.service;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.BoundSetOperations;
-import org.springframework.data.redis.core.HashOperations;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.core.ValueOperations;
-import org.springframework.stereotype.Component;
-
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
-/**
- * spring redis 工具类
- *
- **/
-@SuppressWarnings(value = { "unchecked", "rawtypes" })
-@Component
-public class RedisService
-{
-    @Autowired
-    public RedisTemplate redisTemplate;
-
-    /**
-     * 缓存基本的对象,Integer、String、实体类等
-     *
-     * @param key 缓存的键值
-     * @param value 缓存的值
-     */
-    public <T> void setCacheObject(final String key, final T value)
-    {
-        redisTemplate.opsForValue().set(key, value);
-    }
-
-    /**
-     * 缓存基本的对象,Integer、String、实体类等
-     *
-     * @param key 缓存的键值
-     * @param value 缓存的值
-     * @param timeout 时间
-     * @param timeUnit 时间颗粒度
-     */
-    public <T> void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit)
-    {
-        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
-    }
-
-    /**
-     * 设置有效时间
-     *
-     * @param key Redis键
-     * @param timeout 超时时间
-     * @return true=设置成功;false=设置失败
-     */
-    public boolean expire(final String key, final long timeout)
-    {
-        return expire(key, timeout, TimeUnit.SECONDS);
-    }
-
-    /**
-     * 设置有效时间
-     *
-     * @param key Redis键
-     * @param timeout 超时时间
-     * @param unit 时间单位
-     * @return true=设置成功;false=设置失败
-     */
-    public boolean expire(final String key, final long timeout, final TimeUnit unit)
-    {
-        return redisTemplate.expire(key, timeout, unit);
-    }
-
-    /**
-     * 获取有效时间
-     *
-     * @param key Redis键
-     * @return 有效时间
-     */
-    public long getExpire(final String key)
-    {
-        return redisTemplate.getExpire(key);
-    }
-
-    /**
-     * 判断 key是否存在
-     *
-     * @param key 键
-     * @return true 存在 false不存在
-     */
-    public Boolean hasKey(String key)
-    {
-        return redisTemplate.hasKey(key);
-    }
-
-    /**
-     * 获得缓存的基本对象。
-     *
-     * @param key 缓存键值
-     * @return 缓存键值对应的数据
-     */
-    public <T> T getCacheObject(final String key)
-    {
-        ValueOperations<String, T> operation = redisTemplate.opsForValue();
-        return operation.get(key);
-    }
-
-    /**
-     * 删除单个对象
-     *
-     * @param key
-     */
-    public boolean deleteObject(final String key)
-    {
-        return redisTemplate.delete(key);
-    }
-
-    /**
-     * 删除集合对象
-     *
-     * @param collection 多个对象
-     * @return
-     */
-    public boolean deleteObject(final Collection collection)
-    {
-        return redisTemplate.delete(collection) > 0;
-    }
-
-
-    /**
-     * 根据前缀删除key
-     *
-     * @param key
-     */
-    public boolean deleteByPrefix(final String key) {
-        final Set keys = redisTemplate.keys(key + "*");
-        if (!Objects.isNull(keys) && keys.size() > 0) {
-            redisTemplate.delete(keys);
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * 缓存List数据
-     *
-     * @param key 缓存的键值
-     * @param dataList 待缓存的List数据
-     * @return 缓存的对象
-     */
-    public <T> long setCacheList(final String key, final List<T> dataList)
-    {
-        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
-        return count == null ? 0 : count;
-    }
-
-    /**
-     * 获得缓存的list对象
-     *
-     * @param key 缓存的键值
-     * @return 缓存键值对应的数据
-     */
-    public <T> List<T> getCacheList(final String key)
-    {
-        return redisTemplate.opsForList().range(key, 0, -1);
-    }
-
-    /**
-     * 缓存Set
-     *
-     * @param key 缓存键值
-     * @param dataSet 缓存的数据
-     * @return 缓存数据的对象
-     */
-    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
-    {
-        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
-        Iterator<T> it = dataSet.iterator();
-        while (it.hasNext())
-        {
-            setOperation.add(it.next());
-        }
-        return setOperation;
-    }
-
-    /**
-     * 获得缓存的set
-     *
-     * @param key
-     * @return
-     */
-    public <T> Set<T> getCacheSet(final String key)
-    {
-        return redisTemplate.opsForSet().members(key);
-    }
-
-    /**
-     * 缓存Map
-     *
-     * @param key
-     * @param dataMap
-     */
-    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
-    {
-        if (dataMap != null) {
-            redisTemplate.opsForHash().putAll(key, dataMap);
-        }
-    }
-
-    /**
-     * 获得缓存的Map
-     *
-     * @param key
-     * @return
-     */
-    public <T> Map<String, T> getCacheMap(final String key)
-    {
-        return redisTemplate.opsForHash().entries(key);
-    }
-
-    /**
-     * 往Hash中存入数据
-     *
-     * @param key Redis键
-     * @param hKey Hash键
-     * @param value 值
-     */
-    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
-    {
-        redisTemplate.opsForHash().put(key, hKey, value);
-    }
-
-    /**
-     * 获取Hash中的数据
-     *
-     * @param key Redis键
-     * @param hKey Hash键
-     * @return Hash中的对象
-     */
-    public <T> T getCacheMapValue(final String key, final String hKey)
-    {
-        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
-        return opsForHash.get(key, hKey);
-    }
-
-    /**
-     * 获取多个Hash中的数据
-     *
-     * @param key Redis键
-     * @param hKeys Hash键集合
-     * @return Hash对象集合
-     */
-    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
-    {
-        return redisTemplate.opsForHash().multiGet(key, hKeys);
-    }
-
-    /**
-     * 删除Hash中的某条数据
-     *
-     * @param key Redis键
-     * @param hKey Hash键
-     * @return 是否成功
-     */
-    public boolean deleteCacheMapValue(final String key, final String hKey)
-    {
-        return redisTemplate.opsForHash().delete(key, hKey) > 0;
-    }
-
-    /**
-     * 获得缓存的基本对象列表
-     *
-     * @param pattern 字符串前缀
-     * @return 对象列表
-     */
-    public Collection<String> keys(final String pattern)
-    {
-        return redisTemplate.keys(pattern);
-    }
-
-
-    public BoundSetOperations getBoundSetOperations(String key){
-        return redisTemplate.boundSetOps(key);
-    }
-}

+ 75 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/utils/CacheUtils.java

@@ -0,0 +1,75 @@
+package com.xunmei.common.redis.utils;
+
+import com.xunmei.common.core.utils.SpringUtils;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.redisson.api.RMap;
+import org.springframework.cache.Cache;
+import org.springframework.cache.CacheManager;
+
+import java.util.Set;
+
+/**
+ * 缓存操作工具类 {@link }
+ *
+ * @author Michelle.Chung
+ * @date 2022/8/13
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+@SuppressWarnings(value = {"unchecked"})
+public class CacheUtils {
+
+    private static final CacheManager CACHE_MANAGER = SpringUtils.getBean(CacheManager.class);
+
+    /**
+     * 获取缓存组内所有的KEY
+     *
+     * @param cacheNames 缓存组名称
+     */
+    public static Set<Object> keys(String cacheNames) {
+        RMap<Object, Object> rmap = (RMap<Object, Object>) CACHE_MANAGER.getCache(cacheNames).getNativeCache();
+        return rmap.keySet();
+    }
+
+    /**
+     * 获取缓存值
+     *
+     * @param cacheNames 缓存组名称
+     * @param key        缓存key
+     */
+    public static <T> T get(String cacheNames, Object key) {
+        Cache.ValueWrapper wrapper = CACHE_MANAGER.getCache(cacheNames).get(key);
+        return wrapper != null ? (T) wrapper.get() : null;
+    }
+
+    /**
+     * 保存缓存值
+     *
+     * @param cacheNames 缓存组名称
+     * @param key        缓存key
+     * @param value      缓存值
+     */
+    public static void put(String cacheNames, Object key, Object value) {
+        CACHE_MANAGER.getCache(cacheNames).put(key, value);
+    }
+
+    /**
+     * 删除缓存值
+     *
+     * @param cacheNames 缓存组名称
+     * @param key        缓存key
+     */
+    public static void evict(String cacheNames, Object key) {
+        CACHE_MANAGER.getCache(cacheNames).evict(key);
+    }
+
+    /**
+     * 清空缓存值
+     *
+     * @param cacheNames 缓存组名称
+     */
+    public static void clear(String cacheNames) {
+        CACHE_MANAGER.getCache(cacheNames).clear();
+    }
+
+}

+ 505 - 0
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/utils/RedisUtils.java

@@ -0,0 +1,505 @@
+package com.xunmei.common.redis.utils;
+
+import com.xunmei.common.core.utils.SpringUtils;
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.redisson.api.*;
+
+import java.text.MessageFormat;
+import java.time.Duration;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * redis 工具类
+ *
+ * @author xunmei
+ * @version 3.1.0 新增
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+@SuppressWarnings(value = {"unchecked", "rawtypes"})
+public class RedisUtils {
+
+    private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);
+
+    /**
+     * 限流
+     *
+     * @param key          限流key
+     * @param rateType     限流类型
+     * @param rate         速率
+     * @param rateInterval 速率间隔
+     * @return -1 表示失败
+     */
+    public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval) {
+        RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);
+        rateLimiter.trySetRate(rateType, rate, rateInterval, RateIntervalUnit.SECONDS);
+        if (rateLimiter.tryAcquire()) {
+            return rateLimiter.availablePermits();
+        } else {
+            return -1L;
+        }
+    }
+
+    /**
+     * 获取客户端实例
+     */
+    public static RedissonClient getClient() {
+        return CLIENT;
+    }
+
+    /**
+     * 发布通道消息
+     *
+     * @param channelKey 通道key
+     * @param msg        发送数据
+     * @param consumer   自定义处理
+     */
+    public static <T> void publish(String channelKey, T msg, Consumer<T> consumer) {
+        RTopic topic = CLIENT.getTopic(channelKey);
+        topic.publish(msg);
+        consumer.accept(msg);
+    }
+
+    public static <T> void publish(String channelKey, T msg) {
+        RTopic topic = CLIENT.getTopic(channelKey);
+        topic.publish(msg);
+    }
+
+    /**
+     * 订阅通道接收消息
+     *
+     * @param channelKey 通道key
+     * @param clazz      消息类型
+     * @param consumer   自定义处理
+     */
+    public static <T> void subscribe(String channelKey, Class<T> clazz, Consumer<T> consumer) {
+        RTopic topic = CLIENT.getTopic(channelKey);
+        topic.addListener(clazz, (channel, msg) -> consumer.accept(msg));
+    }
+
+    /**
+     * 缓存基本的对象,Integer、String、实体类等
+     *
+     * @param key   缓存的键值
+     * @param value 缓存的值
+     */
+    public static <T> void setCacheObject(final String key, final T value) {
+        setCacheObject(key, value, false);
+    }
+
+    /**
+     * 缓存基本的对象,保留当前对象 TTL 有效期
+     *
+     * @param key       缓存的键值
+     * @param value     缓存的值
+     * @param isSaveTtl 是否保留TTL有效期(例如: set之前ttl剩余90 set之后还是为90)
+     * @since Redis 6.X 以上使用 setAndKeepTTL 兼容 5.X 方案
+     */
+    public static <T> void setCacheObject(final String key, final T value, final boolean isSaveTtl) {
+        RBucket<T> bucket = CLIENT.getBucket(key);
+        if (isSaveTtl) {
+            try {
+                bucket.setAndKeepTTL(value);
+            } catch (Exception e) {
+                long timeToLive = bucket.remainTimeToLive();
+                setCacheObject(key, value, Duration.ofMillis(timeToLive));
+            }
+        } else {
+            bucket.set(value);
+        }
+    }
+
+    /**
+     * 缓存基本的对象,Integer、String、实体类等
+     *
+     * @param key      缓存的键值
+     * @param value    缓存的值
+     * @param duration 时间
+     */
+    public static <T> void setCacheObject(final String key, final T value, final Duration duration) {
+        RBatch batch = CLIENT.createBatch();
+        RBucketAsync<T> bucket = batch.getBucket(key);
+        bucket.setAsync(value);
+        bucket.expireAsync(duration);
+        batch.execute();
+    }
+
+
+    /**
+     * 如果不存在则设置 并返回 true 如果存在则返回 false
+     *
+     * @param key   缓存的键值
+     * @param value 缓存的值
+     * @return set成功或失败
+     */
+    public static <T> boolean setObjectIfAbsent(final String key, final T value, final Duration duration) {
+        RBucket<T> bucket = CLIENT.getBucket(key);
+        return bucket.setIfAbsent(value, duration);
+    }
+
+    /**
+     * 注册对象监听器
+     * <p>
+     * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
+     *
+     * @param key      缓存的键值
+     * @param listener 监听器配置
+     */
+    public static <T> void addObjectListener(final String key, final ObjectListener listener) {
+        RBucket<T> result = CLIENT.getBucket(key);
+        result.addListener(listener);
+    }
+
+    /**
+     * 设置有效时间
+     *
+     * @param key     Redis键
+     * @param timeout 超时时间
+     * @return true=设置成功;false=设置失败
+     */
+    public static boolean expire(final String key, final long timeout) {
+        return expire(key, Duration.ofSeconds(timeout));
+    }
+
+    /**
+     * 设置有效时间
+     *
+     * @param key      Redis键
+     * @param duration 超时时间
+     * @return true=设置成功;false=设置失败
+     */
+    public static boolean expire(final String key, final Duration duration) {
+        RBucket rBucket = CLIENT.getBucket(key);
+        return rBucket.expire(duration);
+    }
+
+    /**
+     * 获得缓存的基本对象。
+     *
+     * @param key 缓存键值
+     * @return 缓存键值对应的数据
+     */
+    public static <T> T getCacheObject(final String key) {
+        RBucket<T> rBucket = CLIENT.getBucket(key);
+        return rBucket.get();
+    }
+
+    /**
+     * 获得key剩余存活时间
+     *
+     * @param key 缓存键值
+     * @return 剩余存活时间
+     */
+    public static <T> long getTimeToLive(final String key) {
+        RBucket<T> rBucket = CLIENT.getBucket(key);
+        return rBucket.remainTimeToLive();
+    }
+
+    /**
+     * 删除单个对象
+     *
+     * @param key 缓存的键值
+     */
+    public static boolean deleteObject(final String key) {
+        return CLIENT.getBucket(key).delete();
+    }
+
+    /**
+     * 删除集合对象
+     *
+     * @param collection 多个对象
+     */
+    public static void deleteObject(final Collection collection) {
+        RBatch batch = CLIENT.createBatch();
+        collection.forEach(t -> {
+            batch.getBucket(t.toString()).deleteAsync();
+        });
+        batch.execute();
+    }
+
+    /**
+     * 根据前缀删除key
+     *
+     * @param key
+     */
+    public static void deleteByPrefix(final String key) {
+        // 删除缓存
+        String keyPattern = MessageFormat.format("{0}*", key);
+        RKeys keys = CLIENT.getKeys();
+        keys.deleteByPattern(keyPattern);
+    }
+
+
+    /**
+     * 检查缓存对象是否存在
+     *
+     * @param key 缓存的键值
+     */
+    public static boolean isExistsObject(final String key) {
+        return CLIENT.getBucket(key).isExists();
+    }
+
+    /**
+     * 缓存List数据
+     *
+     * @param key      缓存的键值
+     * @param dataList 待缓存的List数据
+     * @return 缓存的对象
+     */
+    public static <T> boolean setCacheList(final String key, final List<T> dataList) {
+        RList<T> rList = CLIENT.getList(key);
+        return rList.addAll(dataList);
+    }
+
+    /**
+     * 注册List监听器
+     * <p>
+     * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
+     *
+     * @param key      缓存的键值
+     * @param listener 监听器配置
+     */
+    public static <T> void addListListener(final String key, final ObjectListener listener) {
+        RList<T> rList = CLIENT.getList(key);
+        rList.addListener(listener);
+    }
+
+    /**
+     * 获得缓存的list对象
+     *
+     * @param key 缓存的键值
+     * @return 缓存键值对应的数据
+     */
+    public static <T> List<T> getCacheList(final String key) {
+        RList<T> rList = CLIENT.getList(key);
+        return rList.readAll();
+    }
+
+    /**
+     * 缓存Set
+     *
+     * @param key     缓存键值
+     * @param dataSet 缓存的数据
+     * @return 缓存数据的对象
+     */
+    public static <T> boolean setCacheSet(final String key, final Set<T> dataSet) {
+        RSet<T> rSet = CLIENT.getSet(key);
+        return rSet.addAll(dataSet);
+    }
+
+    /**
+     * 注册Set监听器
+     * <p>
+     * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
+     *
+     * @param key      缓存的键值
+     * @param listener 监听器配置
+     */
+    public static <T> void addSetListener(final String key, final ObjectListener listener) {
+        RSet<T> rSet = CLIENT.getSet(key);
+        rSet.addListener(listener);
+    }
+
+    /**
+     * 获得缓存的set
+     *
+     * @param key 缓存的key
+     * @return set对象
+     */
+    public static <T> Set<T> getCacheSet(final String key) {
+        RSet<T> rSet = CLIENT.getSet(key);
+        return rSet.readAll();
+    }
+
+    /**
+     * 缓存Map
+     *
+     * @param key     缓存的键值
+     * @param dataMap 缓存的数据
+     */
+    public static <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
+        if (dataMap != null) {
+            RMap<String, T> rMap = CLIENT.getMap(key);
+            rMap.putAll(dataMap);
+        }
+    }
+
+    /**
+     * 注册Map监听器
+     * <p>
+     * key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
+     *
+     * @param key      缓存的键值
+     * @param listener 监听器配置
+     */
+    public static <T> void addMapListener(final String key, final ObjectListener listener) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        rMap.addListener(listener);
+    }
+
+    /**
+     * 获得缓存的Map
+     *
+     * @param key 缓存的键值
+     * @return map对象
+     */
+    public static <T> Map<String, T> getCacheMap(final String key) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        return rMap.getAll(rMap.keySet());
+    }
+
+    /**
+     * 获得缓存Map的key列表
+     *
+     * @param key 缓存的键值
+     * @return key列表
+     */
+    public static <T> Set<String> getCacheMapKeySet(final String key) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        return rMap.keySet();
+    }
+
+    /**
+     * 往Hash中存入数据
+     *
+     * @param key   Redis键
+     * @param hKey  Hash键
+     * @param value 值
+     */
+    public static <T> void setCacheMapValue(final String key, final String hKey, final T value) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        rMap.put(hKey, value);
+    }
+
+    /**
+     * 获取Hash中的数据
+     *
+     * @param key  Redis键
+     * @param hKey Hash键
+     * @return Hash中的对象
+     */
+    public static <T> T getCacheMapValue(final String key, final String hKey) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        return rMap.get(hKey);
+    }
+
+    /**
+     * 删除Hash中的数据
+     *
+     * @param key  Redis键
+     * @param hKey Hash键
+     * @return Hash中的对象
+     */
+    public static <T> T delCacheMapValue(final String key, final String hKey) {
+        RMap<String, T> rMap = CLIENT.getMap(key);
+        return rMap.remove(hKey);
+    }
+
+    /**
+     * 删除Hash中的数据
+     *
+     * @param key   Redis键
+     * @param hKeys Hash键
+     */
+    public static <T> void delMultiCacheMapValue(final String key, final Set<String> hKeys) {
+        RBatch batch = CLIENT.createBatch();
+        RMapAsync<String, T> rMap = batch.getMap(key);
+        for (String hKey : hKeys) {
+            rMap.removeAsync(hKey);
+        }
+        batch.execute();
+    }
+
+    /**
+     * 获取多个Hash中的数据
+     *
+     * @param key   Redis键
+     * @param hKeys Hash键集合
+     * @return Hash对象集合
+     */
+    public static <K, V> Map<K, V> getMultiCacheMapValue(final String key, final Set<K> hKeys) {
+        RMap<K, V> rMap = CLIENT.getMap(key);
+        return rMap.getAll(hKeys);
+    }
+
+    /**
+     * 设置原子值
+     *
+     * @param key   Redis键
+     * @param value 值
+     */
+    public static void setAtomicValue(String key, long value) {
+        RAtomicLong atomic = CLIENT.getAtomicLong(key);
+        atomic.set(value);
+    }
+
+    /**
+     * 获取原子值
+     *
+     * @param key Redis键
+     * @return 当前值
+     */
+    public static long getAtomicValue(String key) {
+        RAtomicLong atomic = CLIENT.getAtomicLong(key);
+        return atomic.get();
+    }
+
+    /**
+     * 递增原子值
+     *
+     * @param key Redis键
+     * @return 当前值
+     */
+    public static long incrAtomicValue(String key) {
+        RAtomicLong atomic = CLIENT.getAtomicLong(key);
+        return atomic.incrementAndGet();
+    }
+
+    /**
+     * 递减原子值
+     *
+     * @param key Redis键
+     * @return 当前值
+     */
+    public static long decrAtomicValue(String key) {
+        RAtomicLong atomic = CLIENT.getAtomicLong(key);
+        return atomic.decrementAndGet();
+    }
+
+    /**
+     * 获得缓存的基本对象列表
+     *
+     * @param pattern 字符串前缀
+     * @return 对象列表
+     */
+    public static Collection<String> keys(final String pattern) {
+        Stream<String> stream = CLIENT.getKeys().getKeysStreamByPattern(pattern);
+        return stream.collect(Collectors.toList());
+    }
+
+    /**
+     * 删除缓存的基本对象列表
+     *
+     * @param pattern 字符串前缀
+     */
+    public static void deleteKeys(final String pattern) {
+        CLIENT.getKeys().deleteByPattern(pattern);
+    }
+
+    /**
+     * 检查redis中是否存在key
+     *
+     * @param key 键
+     */
+    public static Boolean hasKey(String key) {
+        RKeys rKeys = CLIENT.getKeys();
+        return rKeys.countExists(key) > 0;
+    }
+
+}

+ 1 - 2
soc-common/soc-common-redis/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

@@ -1,2 +1 @@
-com.xunmei.common.redis.configure.RedisConfig
-com.xunmei.common.redis.service.RedisService
+com.xunmei.common.redis.config.RedisConfiguration

+ 10 - 7
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/service/TokenService.java

@@ -7,7 +7,7 @@ import com.xunmei.common.core.utils.ServletUtils;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.utils.ip.IpUtils;
 import com.xunmei.common.core.utils.uuid.IdUtils;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.system.api.RemoteUserService;
 import com.xunmei.system.api.model.LoginUser;
@@ -15,6 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 import javax.servlet.http.HttpServletRequest;
+import java.time.Duration;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -27,8 +28,6 @@ import java.util.concurrent.TimeUnit;
  */
 @Component
 public class TokenService {
-    @Autowired
-    private RedisService redisService;
 
     @Autowired
     private RemoteUserService remoteUserService;
@@ -101,7 +100,8 @@ public class TokenService {
         try {
             if (StringUtils.isNotEmpty(token)) {
                 String userkey = JwtUtils.getUserKey(token);
-                user = redisService.getCacheObject(getTokenKey(userkey));
+                user = RedisUtils.getCacheObject(getTokenKey(userkey));
+                //user = redisService.getCacheObject(getTokenKey(userkey));
                 return user;
             }
         } catch (Exception e) {
@@ -124,7 +124,8 @@ public class TokenService {
     public void delLoginUser(String token) {
         if (StringUtils.isNotEmpty(token)) {
             String userkey = JwtUtils.getUserKey(token);
-            redisService.deleteObject(getTokenKey(userkey));
+            //redisService.deleteObject(getTokenKey(userkey));
+            RedisUtils.deleteObject(getTokenKey(userkey));
         }
     }
 
@@ -153,8 +154,10 @@ public class TokenService {
         String userKey = getTokenKey(loginUser.getToken());
         remoteUserService.userLoginInfo(loginUser.getUserid(), new Date(), loginUser.getIpaddr(), SecurityConstants.INNER);
         //登陆后删除之前的token
-        redisService.deleteByPrefix(userKey);
-        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
+        RedisUtils.deleteByPrefix(userKey);
+        RedisUtils.setCacheObject(userKey, loginUser, Duration.ofMinutes(expireTime));
+        //redisService.deleteByPrefix(userKey);
+        // redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
     }
 
     private String getTokenKey(String token) {

+ 25 - 28
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/DictUtils.java

@@ -4,74 +4,71 @@ import com.alibaba.fastjson2.JSONArray;
 import com.xunmei.common.core.constant.CacheConstants;
 import com.xunmei.common.core.utils.SpringUtils;
 import com.xunmei.common.core.utils.StringUtils;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.system.api.domain.SysDictData;
-import com.xunmei.system.api.domain.SysDictDetail;
 
 import java.util.Collection;
 import java.util.List;
 
 /**
  * 字典工具类
- * 
+ *
  * @author xunmei
  */
-public class DictUtils
-{
+public class DictUtils {
     /**
      * 设置字典缓存
-     * 
-     * @param key 参数键
+     *
+     * @param key       参数键
      * @param dictDatas 字典数据列表
      */
-    public static void setDictCache(String key, List<SysDictData> dictDatas)
-    {
-        SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas);
+    public static void setDictCache(String key, List<SysDictData> dictDatas) {
+        RedisUtils.setCacheObject(getCacheKey(key), dictDatas);
+        //SpringUtils.getBean(RedisService.class).setCacheObject(getCacheKey(key), dictDatas);
     }
 
     /**
      * 获取字典缓存
-     * 
+     *
      * @param key 参数键
      * @return dictDatas 字典数据列表
      */
-    public static List<SysDictData> getDictCache(String key)
-    {
-        JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(getCacheKey(key));
-        if (StringUtils.isNotNull(arrayCache))
-        {
-            return arrayCache.toList(SysDictData.class);
+    public static List<SysDictData> getDictCache(String key) {
+        List<SysDictData> arrayCache = RedisUtils.getCacheObject(getCacheKey(key));
+        //JSONArray arrayCache = SpringUtils.getBean(RedisService.class).getCacheObject(getCacheKey(key));
+        if (StringUtils.isNotNull(arrayCache)) {
+//            return arrayCache.toList(SysDictData.class);
+            return arrayCache;
         }
         return null;
     }
 
     /**
      * 删除指定字典缓存
-     * 
+     *
      * @param key 字典键
      */
-    public static void removeDictCache(String key)
-    {
-        SpringUtils.getBean(RedisService.class).deleteObject(getCacheKey(key));
+    public static void removeDictCache(String key) {
+        RedisUtils.deleteObject(getCacheKey(key));
+//        SpringUtils.getBean(RedisService.class).deleteObject(getCacheKey(key));
     }
 
     /**
      * 清空字典缓存
      */
-    public static void clearDictCache()
-    {
-        Collection<String> keys = SpringUtils.getBean(RedisService.class).keys(CacheConstants.SYS_DICT_KEY + "*");
-        SpringUtils.getBean(RedisService.class).deleteObject(keys);
+    public static void clearDictCache() {
+        RedisUtils.deleteByPrefix(CacheConstants.SYS_DICT_KEY);
+//        Collection<String> keys = SpringUtils.getBean(RedisService.class).keys(CacheConstants.SYS_DICT_KEY + "*");
+//        SpringUtils.getBean(RedisService.class).deleteObject(keys);
     }
 
     /**
      * 设置cache key
-     * 
+     *
      * @param configKey 参数键
      * @return 缓存键key
      */
-    public static String getCacheKey(String configKey)
-    {
+    public static String getCacheKey(String configKey) {
         return CacheConstants.SYS_DICT_KEY + configKey;
     }
 }

+ 5 - 6
soc-gateway/src/main/java/com/xunmei/gateway/filter/AuthFilter.java

@@ -7,7 +7,7 @@ import com.xunmei.common.core.constant.TokenConstants;
 import com.xunmei.common.core.utils.JwtUtils;
 import com.xunmei.common.core.utils.ServletUtils;
 import com.xunmei.common.core.utils.StringUtils;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.gateway.config.properties.IgnoreWhiteProperties;
 import io.jsonwebtoken.Claims;
 import org.slf4j.Logger;
@@ -23,7 +23,7 @@ import reactor.core.publisher.Mono;
 
 /**
  * 网关鉴权
- * 
+ *
  * @author xunmei
  */
 @Component
@@ -35,8 +35,6 @@ public class AuthFilter implements GlobalFilter, Ordered
     @Autowired
     private IgnoreWhiteProperties ignoreWhite;
 
-    @Autowired
-    private RedisService redisService;
 
 
     @Override
@@ -62,7 +60,8 @@ public class AuthFilter implements GlobalFilter, Ordered
             return unauthorizedResponse(exchange, "令牌已过期或验证不正确!");
         }
         String userkey = JwtUtils.getUserKey(claims);
-        boolean islogin = redisService.hasKey(getTokenKey(userkey));
+        boolean islogin = RedisUtils.hasKey(getTokenKey(userkey));
+        //boolean islogin = redisService.hasKey(getTokenKey(userkey));
         if (!islogin)
         {
             return unauthorizedResponse(exchange, "登录状态已过期");
@@ -132,4 +131,4 @@ public class AuthFilter implements GlobalFilter, Ordered
     {
         return -200;
     }
-}
+}

+ 8 - 8
soc-gateway/src/main/java/com/xunmei/gateway/service/impl/ValidateCodeServiceImpl.java

@@ -8,7 +8,7 @@ import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.utils.sign.Base64;
 import com.xunmei.common.core.utils.uuid.IdUtils;
 import com.xunmei.common.core.web.domain.AjaxResult;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.gateway.config.properties.CaptchaProperties;
 import com.xunmei.gateway.service.ValidateCodeService;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -19,7 +19,7 @@ import javax.annotation.Resource;
 import javax.imageio.ImageIO;
 import java.awt.image.BufferedImage;
 import java.io.IOException;
-import java.util.concurrent.TimeUnit;
+import java.time.Duration;
 
 /**
  * 验证码实现处理
@@ -35,8 +35,6 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
     @Resource(name = "captchaProducerMath")
     private Producer captchaProducerMath;
 
-    @Autowired
-    private RedisService redisService;
 
     @Autowired
     private CaptchaProperties captchaProperties;
@@ -76,8 +74,8 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
             capStr = code = captchaProducer.createText();
             image = captchaProducer.createImage(capStr);
         }
-
-        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
+        RedisUtils.setCacheObject(verifyKey,code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
+        //redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
         // 转换流信息写出
         FastByteArrayOutputStream os = new FastByteArrayOutputStream();
         try
@@ -109,8 +107,10 @@ public class ValidateCodeServiceImpl implements ValidateCodeService
             throw new CaptchaException("验证码已失效");
         }
         String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
-        String captcha = redisService.getCacheObject(verifyKey);
-        redisService.deleteObject(verifyKey);
+        String captcha = RedisUtils.getCacheObject(verifyKey);
+//        String captcha = redisService.getCacheObject(verifyKey);
+        RedisUtils.deleteObject(verifyKey);
+        //redisService.deleteObject(verifyKey);
 
         if (!code.equalsIgnoreCase(captcha))
         {

+ 16 - 9
soc-modules/soc-modules-core/src/main/java/com/xunmei/core/resumption/controller/ResumptionController.java

@@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSON;
 import com.xunmei.common.core.constant.SecurityConstants;
 import com.xunmei.common.core.constant.SystemParameterConstant;
 import com.xunmei.common.core.web.domain.AjaxResult;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.core.resumption.domain.Resumption;
 import com.xunmei.core.resumption.dto.ResumptionTaskDataDto;
@@ -27,6 +27,7 @@ import org.springframework.web.bind.annotation.RestController;
 import javax.validation.Valid;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
+import java.time.Duration;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -40,8 +41,7 @@ public class ResumptionController {
     RemoteConfigService remoteConfigService;
     @Autowired
     ResumptionService resumptionService;
-    @Autowired
-    private RedisService redisService;
+
     @ApiOperation(value = "所有")
     @PostMapping(value = "/taskList")
     AjaxResult taskList(@RequestBody @Valid final ResumptionTaskDto request) throws ParseException {
@@ -93,9 +93,13 @@ public class ResumptionController {
     @PostMapping(value = "/submitTaskData")
     AjaxResult submitTaskData( @RequestBody @Valid final ResumptionTaskDataDto request) throws ParseException {
         //仅当hashKey不存在时才设置
-        boolean flag =redisService.redisTemplate.opsForHash().putIfAbsent("resumption"+request.getTaskid(),request.getTaskid(),request.getTaskid());//redisTemplate.opsForValue().setIfAbsent("resumption"+request.getTaskid(), "resumption"+request.getTaskid());
-        redisService.redisTemplate.expire("resumption"+request.getTaskid(),1000*20, TimeUnit.MILLISECONDS);
-        if(!flag){
+        Boolean isOk = RedisUtils.hasKey("resumption" + request.getTaskid());
+        if(!isOk){
+            RedisUtils.setCacheObject("resumption"+request.getTaskid(),request.getTaskid(), Duration.ofMillis(1000*20));
+        }
+        /*boolean flag =redisService.redisTemplate.opsForHash().putIfAbsent("resumption"+request.getTaskid(),request.getTaskid(),request.getTaskid());//redisTemplate.opsForValue().setIfAbsent("resumption"+request.getTaskid(), "resumption"+request.getTaskid());
+        redisService.redisTemplate.expire("resumption"+request.getTaskid(),1000*20, TimeUnit.MILLISECONDS);*/
+        if(!isOk){
             throw  new RuntimeException("请勿重复提交");
         }else{
             try {
@@ -109,13 +113,16 @@ public class ResumptionController {
                     throw new RuntimeException("该任务已过期不能完成提交");
                 }
                 int num = this.resumptionBusiness.submitTaskData(request, SecurityUtils.getLoginUser(),resumption);
-                redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
+                RedisUtils.deleteObject("resumption"+request.getTaskid());
+                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
                 return AjaxResult.success(num);
             }catch (Exception e){
-                redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
+                RedisUtils.deleteObject("resumption"+request.getTaskid());
+                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
                 return AjaxResult.error(e.getMessage());
             }finally {
-                redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
+                RedisUtils.deleteObject("resumption"+request.getTaskid());
+                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
             }
         }
 

+ 2 - 5
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/controller/SysLogininforController.java

@@ -6,10 +6,9 @@ import com.xunmei.common.core.web.domain.AjaxResult;
 import com.xunmei.common.core.web.page.TableDataInfo;
 import com.xunmei.common.log.annotation.Log;
 import com.xunmei.common.log.enums.BusinessType;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.annotation.InnerAuth;
 import com.xunmei.common.security.annotation.RequiresPermissions;
-import com.xunmei.system.api.domain.SysDictType;
 import com.xunmei.system.api.domain.SysLogininfor;
 import com.xunmei.system.service.ISysLogininforService;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -30,8 +29,6 @@ public class SysLogininforController extends BaseController
     @Autowired
     private ISysLogininforService logininforService;
 
-    @Autowired
-    private RedisService redisService;
 
     @RequiresPermissions("system:logininfor:list")
     @GetMapping("/list")
@@ -70,7 +67,7 @@ public class SysLogininforController extends BaseController
     @GetMapping("/unlock/{userName}")
     public AjaxResult unlock(@PathVariable("userName") String userName)
     {
-        redisService.deleteObject(CacheConstants.PWD_ERR_CNT_KEY + userName);
+        RedisUtils.deleteObject(CacheConstants.PWD_ERR_CNT_KEY + userName);
         return success();
     }
 

+ 5 - 7
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/controller/SysUserOnlineController.java

@@ -7,7 +7,7 @@ import com.xunmei.common.core.web.domain.AjaxResult;
 import com.xunmei.common.core.web.page.TableDataInfo;
 import com.xunmei.common.log.annotation.Log;
 import com.xunmei.common.log.enums.BusinessType;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.annotation.RequiresPermissions;
 import com.xunmei.system.api.model.LoginUser;
 import com.xunmei.system.domain.SysUserOnline;
@@ -15,7 +15,6 @@ import com.xunmei.system.service.ISysUserOnlineService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
-import javax.annotation.Resource;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -33,18 +32,17 @@ public class SysUserOnlineController extends BaseController
     @Autowired
     private ISysUserOnlineService userOnlineService;
 
-    @Resource
-    private RedisService redisService;
 
     @RequiresPermissions("monitor:online:list")
     @GetMapping("/list")
     public TableDataInfo<SysUserOnline> list(String ipaddr, String userName)
     {
-        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
+        Collection<String> keys = RedisUtils.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
         List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
         for (String key : keys)
         {
-            LoginUser user = redisService.getCacheObject(key);
+            LoginUser user = RedisUtils.getCacheObject(key);
+            //LoginUser user = redisService.getCacheObject(key);
             if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
             {
                 userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
@@ -77,7 +75,7 @@ public class SysUserOnlineController extends BaseController
     @DeleteMapping("/{tokenId}")
     public AjaxResult forceLogout(@PathVariable String tokenId)
     {
-        redisService.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
+        RedisUtils.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
         return success();
     }
 }

+ 18 - 12
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysConfigServiceImpl.java

@@ -9,7 +9,7 @@ import com.xunmei.common.core.exception.ServiceException;
 import com.xunmei.common.core.text.Convert;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.web.page.TableDataInfo;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.system.api.domain.SysConfig;
 import com.xunmei.system.mapper.SysConfigMapper;
 import com.xunmei.system.service.ISysConfigService;
@@ -31,8 +31,6 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
     @Autowired
     private SysConfigMapper configMapper;
 
-    @Autowired
-    private RedisService redisService;
 
     /**
      * 项目启动时,初始化参数到缓存
@@ -83,7 +81,8 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
     @Override
     public String selectConfigByKey(String configKey)
     {
-        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
+        String configValue = Convert.toStr(RedisUtils.getCacheObject(getCacheKey(configKey)));
+        //String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
         if (StringUtils.isNotEmpty(configValue))
         {
             return configValue;
@@ -93,7 +92,8 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
         SysConfig retConfig = configMapper.selectConfig(config);
         if (StringUtils.isNotNull(retConfig))
         {
-            redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
+            RedisUtils.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
+            //redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
             return retConfig.getConfigValue();
         }
         return StringUtils.EMPTY;
@@ -123,7 +123,8 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
         int row = configMapper.insertConfig(config);
         if (row > 0)
         {
-            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            RedisUtils.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            //redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
         }
         return row;
     }
@@ -140,13 +141,15 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
         SysConfig temp = configMapper.selectConfigById(config.getConfigId());
         if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey()))
         {
-            redisService.deleteObject(getCacheKey(temp.getConfigKey()));
+            RedisUtils.deleteObject(getCacheKey(temp.getConfigKey()));
+            //redisService.deleteObject(getCacheKey(temp.getConfigKey()));
         }
 
         int row = configMapper.updateConfig(config);
         if (row > 0)
         {
-            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            RedisUtils.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            //redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
         }
         return row;
     }
@@ -167,7 +170,8 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
                 throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
             }
             configMapper.deleteConfigById(configId);
-            redisService.deleteObject(getCacheKey(config.getConfigKey()));
+            RedisUtils.deleteObject(getCacheKey(config.getConfigKey()));
+            //redisService.deleteObject(getCacheKey(config.getConfigKey()));
         }
     }
 
@@ -180,7 +184,8 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
         List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
         for (SysConfig config : configsList)
         {
-            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            RedisUtils.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
+            //redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
         }
     }
 
@@ -190,8 +195,9 @@ public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig
     @Override
     public void clearConfigCache()
     {
-        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
-        redisService.deleteObject(keys);
+        /*Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
+        redisService.deleteObject(keys);*/
+        RedisUtils.deleteByPrefix(CacheConstants.SYS_CONFIG_KEY);
     }
 
     /**

+ 9 - 3
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysDeptServiceImpl.java

@@ -12,7 +12,7 @@ import com.xunmei.common.core.text.Convert;
 import com.xunmei.common.core.utils.SpringUtils;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.datascope.annotation.DataScope;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.system.api.domain.SysDept;
 import com.xunmei.system.api.domain.SysOrg;
@@ -23,6 +23,7 @@ import com.xunmei.system.mapper.SysDeptMapper;
 import com.xunmei.system.mapper.SysOrgMapper;
 import com.xunmei.system.mapper.SysRoleMapper;
 import com.xunmei.system.service.ISysDeptService;
+import com.xunmei.system.service.ISysOrgService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
@@ -45,7 +46,7 @@ public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> impl
     private SysOrgMapper orgMapper;
 
     @Autowired
-    private RedisService redisService;
+    private ISysOrgService orgService;
 
 
     /**
@@ -114,7 +115,12 @@ public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> impl
         if (ObjectUtil.isNull(sysOrg)) {
             throw new ServiceException("当前用户没有部门信息");
         }
-        List<SysOrg> cacheList = redisService.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
+        //List<SysOrg> cacheList = redisService.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
+        Boolean isOk = RedisUtils.hasKey(CacheConstants.ORG_CACHE_LIST_KEY);
+        if(!isOk){
+            orgService.loadingOrgCache();
+        }
+        List<SysOrg> cacheList = RedisUtils.getCacheList(CacheConstants.ORG_CACHE_LIST_KEY);
         List<SysOrg> orgs = new ArrayList<>();
         for (SysOrg org : cacheList) {
             String path = org.getPath();

+ 5 - 8
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysOrgServiceImpl.java

@@ -9,14 +9,11 @@ import com.xunmei.common.core.constant.CacheConstants;
 import com.xunmei.common.core.constant.Constants;
 import com.xunmei.common.core.exception.ServiceException;
 import com.xunmei.common.core.utils.DateUtils;
-import com.xunmei.common.core.utils.SpringUtils;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.web.page.TableDataInfo;
-import com.xunmei.common.redis.service.RedisService;
+import com.xunmei.common.redis.utils.RedisUtils;
 import com.xunmei.common.security.utils.SecurityUtils;
-import com.xunmei.system.api.domain.SysDept;
 import com.xunmei.system.api.domain.SysOrg;
-import com.xunmei.system.domain.vo.TreeSelect;
 import com.xunmei.system.mapper.SysOrgMapper;
 import com.xunmei.system.mapper.SysUserMapper;
 import com.xunmei.system.service.ISysOrgService;
@@ -44,8 +41,6 @@ public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> impleme
     @Autowired
     private SysUserMapper sysUserMapper;
 
-    @Autowired
-    private RedisService redisService;
 
 
     /**
@@ -252,12 +247,14 @@ public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> impleme
         qw.lambda().ge(SysOrg::getDeleted, 0);
         List<SysOrg> list = baseMapper.selectList(qw);
         clearOrgCache();
-        redisService.setCacheList(CacheConstants.ORG_CACHE_LIST_KEY, list);
+        RedisUtils.setCacheList(CacheConstants.ORG_CACHE_LIST_KEY, list);
+        //redisService.setCacheList(CacheConstants.ORG_CACHE_LIST_KEY, list);
     }
 
     @Override
     public void clearOrgCache() {
-        redisService.deleteObject(CacheConstants.ORG_CACHE_LIST_KEY);
+        RedisUtils.deleteObject(CacheConstants.ORG_CACHE_LIST_KEY);
+        //redisService.deleteObject(CacheConstants.ORG_CACHE_LIST_KEY);
     }
 
     @Override