tianwu.sun пре 1 месец
родитељ
комит
70bc95c312

+ 1 - 3
src/main/java/com/bootdo/common/redis/shiro/RedisCacheManager.java

@@ -21,7 +21,7 @@ public class RedisCacheManager implements CacheManager {
     // fast lookup by name map
     private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
 
-    private RedisManager redisManager;
+    private RedisManager redisManager ;
 
     /**
      * The Redis key prefix for caches
@@ -54,8 +54,6 @@ public class RedisCacheManager implements CacheManager {
 
         if (c == null) {
 
-            // initialize the Redis manager instance
-            redisManager.init();
 
             // create a new cache instance
             c = new RedisCache<K, V>(redisManager, keyPrefix);

+ 27 - 205
src/main/java/com/bootdo/common/redis/shiro/RedisManager.java

@@ -5,83 +5,40 @@ package com.bootdo.common.redis.shiro;
  * @version V1.0
  */
 
-import java.nio.charset.StandardCharsets;
-import java.util.HashSet;
-import java.util.List;
+
 import java.util.Set;
 
-import org.springframework.beans.factory.annotation.Value;
-import redis.clients.jedis.*;
+import com.bootdo.common.utils.RedisUtil;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
 
 /**
  *
  */
+@Component
 public class RedisManager {
-
-    @Value("${spring.redis.host}")
-    private String host = "127.0.0.1";
-
-    @Value("${spring.redis.port}")
-    private int port = 6379;
-
+    @Resource
+    private RedisUtil redisUtil;
     // 0 - never expire
     private int expire = 0;
 
-    //timeout for jedis try to connect to redis server, not expire time! In milliseconds
-    @Value("${spring.redis.timeout}")
-    private int timeout = 0;
-
-    @Value("${spring.redis.password}")
-    private String password = "";
-
-    private static Jedis jedis = null;
-    private static JedisCluster jedisCluster = null;
-
     public RedisManager() {
 
     }
-
     /**
-     * 初始化方法
+     * 获得byte[]型的key
+     * @param key
+     * @return
      */
-    public void init() {
-        if (host.contains(",")) {
-            if(jedisCluster == null){
-                JedisPoolConfig config = new JedisPoolConfig();
-                config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
-                config.setLifo(true);
-                config.setMaxIdle(30);
-                config.setMaxTotal(30);
-                config.setMaxWaitMillis(-1);
-                config.setMinEvictableIdleTimeMillis(3600000);
-                config.setNumTestsPerEvictionRun(3);
-                config.setSoftMinEvictableIdleTimeMillis(3600000);
-                String[] addrs = host.split(",");
-                Set<HostAndPort> nodes = new HashSet<>();
-                for (int i = 0; i < addrs.length; i++) {
-                    nodes.add(new HostAndPort(addrs[i].split(":")[0], Integer.parseInt(addrs[i].split(":")[1])));
-                }
-
-                jedisCluster = new JedisCluster(nodes, 10000, 10000, 100, password, config);//xxxx是Redis的密码
-
-            }
-
-        } else {
-            if (jedis == null) {
-                if (password != null && !"".equals(password)) {
-                    jedis = new JedisPool(new JedisPoolConfig(), host, port, timeout, password).getResource();
-                } else if (timeout != 0) {
-                    jedis = new JedisPool(new JedisPoolConfig(), host, port, timeout).getResource();
-                } else {
-                    jedis = new JedisPool(new JedisPoolConfig(), host, port).getResource();
-                }
-
-            }
+    private byte[] getByteKey(Object key){
+        if(key instanceof String){
+            return ((String)key).getBytes();
+        }else{
+            return SerializeUtils.serialize(key);
         }
-
     }
 
-
     /**
      * get value from redis
      *
@@ -89,20 +46,7 @@ public class RedisManager {
      * @return
      */
     public byte[] get(byte[] key) {
-        byte[] value = null;
-
-        try {
-            if(jedisCluster != null){
-                value = jedisCluster.get(key);
-            } else {
-                value = jedis.get(key);
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        byte[] value = redisUtil.get(key);
         return value;
     }
 
@@ -114,24 +58,11 @@ public class RedisManager {
      * @return
      */
     public byte[] set(byte[] key, byte[] value) {
-
-        try {
-            if(jedisCluster != null){
-                jedisCluster.set(key, value);
-                if (this.expire != 0) {
-                    jedisCluster.expire(key, this.expire);
-                }
-            } else {
-                jedis.set(key, value);
-                if (this.expire != 0) {
-                    jedis.expire(key, this.expire);
-                }
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
+        redisUtil.set(key, value,this.expire);
+        if (this.expire != 0) {
+            redisUtil.set(key, value,this.expire);
+        } else {
+            redisUtil.set(key, value);
         }
         return value;
     }
@@ -145,25 +76,7 @@ public class RedisManager {
      * @return
      */
     public byte[] set(byte[] key, byte[] value, int expire) {
-
-        try {
-            if(jedisCluster != null){
-                jedisCluster.set(key, value);
-                if (expire != 0) {
-                    jedisCluster.expire(key, expire);
-                }
-            } else {
-                jedis.set(key, value);
-                if (expire != 0) {
-                    jedis.expire(key, expire);
-                }
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        redisUtil.set(key, value,expire);
         return value;
     }
 
@@ -173,56 +86,21 @@ public class RedisManager {
      * @param key
      */
     public void del(byte[] key) {
-        try {
-            if(jedisCluster != null){
-                jedisCluster.del(key);
-            } else {
-                jedis.del(key);
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        redisUtil.del(key);
     }
 
     /**
      * flush
      */
     public void flushDB() {
-
-        try {
-            if(jedisCluster != null){
-                jedisCluster.flushDB();
-            } else {
-                jedis.flushDB();
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        //do nothing
     }
 
     /**
      * size
      */
     public Long dbSize() {
-        Long dbSize = 0L;
-        try {
-            if(jedisCluster != null){
-                dbSize = jedis.dbSize();
-            } else {
-                dbSize = jedis.dbSize();
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        Long dbSize = redisUtil.dbSize();
         return dbSize;
     }
 
@@ -232,50 +110,10 @@ public class RedisManager {
      * @return
      */
     public Set<byte[]> keys(String pattern) {
-        Set<byte[]> keys = new HashSet<>();
-        try {
-            if(jedisCluster != null){
-                Set<String> keysStr = new HashSet<>();
-                String cursor = "0";
-                ScanParams scanParams = new ScanParams().match(pattern).count(100);
-                do {
-                    ScanResult<String> scanResult = jedisCluster.scan(cursor, scanParams);
-                    List<String> result = scanResult.getResult();
-                    keysStr.addAll(result);
-                    cursor = scanResult.getStringCursor();
-                } while (!"0".equals(cursor));
-
-                for (String str : keysStr) {
-                    byte[] byteArray = str.getBytes(StandardCharsets.UTF_8); // 将字符串转换为UTF-8编码的字节数组
-                    keys.add(byteArray); // 将字节数组添加到新的集合中
-                }
-            } else {
-                keys = jedis.keys(pattern.getBytes());
-            }
-
-        } finally {
-            if (jedis != null) {
-                jedis.close();
-            }
-        }
+        Set<byte[]> keys = redisUtil.keys(pattern.getBytes());
         return keys;
     }
 
-    public String getHost() {
-        return host;
-    }
-
-    public void setHost(String host) {
-        this.host = host;
-    }
-
-    public int getPort() {
-        return port;
-    }
-
-    public void setPort(int port) {
-        this.port = port;
-    }
 
     public int getExpire() {
         return expire;
@@ -285,21 +123,5 @@ public class RedisManager {
         this.expire = expire;
     }
 
-    public int getTimeout() {
-        return timeout;
-    }
-
-    public void setTimeout(int timeout) {
-        this.timeout = timeout;
-    }
-
-    public String getPassword() {
-        return password;
-    }
-
-    public void setPassword(String password) {
-        this.password = password;
-    }
-
 
 }

+ 0 - 6
src/main/java/com/bootdo/common/redis/shiro/RedisSessionDAO.java

@@ -97,7 +97,6 @@ public class RedisSessionDAO extends AbstractSessionDAO {
 
     /**
      * 获得byte[]型的key
-     * @param key
      * @return
      */
     private byte[] getByteKey(Serializable sessionId){
@@ -111,11 +110,6 @@ public class RedisSessionDAO extends AbstractSessionDAO {
 
     public void setRedisManager(RedisManager redisManager) {
         this.redisManager = redisManager;
-
-        /**
-         * 初始化redisManager
-         */
-        this.redisManager.init();
     }
 
     /**

+ 50 - 3
src/main/java/com/bootdo/common/utils/RedisUtil.java

@@ -1,7 +1,10 @@
 package com.bootdo.common.utils;
 
 
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.connection.RedisStringCommands;
 import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
 import org.springframework.data.redis.support.atomic.RedisAtomicLong;
 
 import java.util.List;
@@ -37,7 +40,8 @@ public class RedisUtil {
             e.printStackTrace();  
             return false;  
         }  
-    }  
+    }
+
 
     /** 
      * 根据key 获取过期时间 
@@ -69,7 +73,17 @@ public class RedisUtil {
     @SuppressWarnings("unchecked")  
     public void del(String key){
         redisTemplate.delete(key);
-    }  
+    }
+
+    /**
+     * 删除缓存
+     * @param key 可以传一个值 或多个
+     */
+    @SuppressWarnings("unchecked")
+    public void del(byte[] key){
+        redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.del(key));
+    }
+
 
     //============================String=============================  
     /** 
@@ -80,6 +94,12 @@ public class RedisUtil {
     public Object get(String key){  
         return key==null?null:redisTemplate.opsForValue().get(key);  
     }
+
+    public byte[] get(byte[] key) {
+        // 使用了lambda表达式
+        return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.get(key));
+    }
+
     /**
      * 普通缓存获取并刷新过期时间
      * @param key 键
@@ -111,8 +131,35 @@ public class RedisUtil {
             return false;  
         }  
 
-    }  
+    }
+
+    public byte[] set(byte[] key,byte[] value) {
+        // 使用了lambda表达式
+        redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.set(key,value));
+        return value;
+    }
+
+    public byte[] set(byte[] key,byte[] value,long time) {
+        // 使用了lambda表达式
+         redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.set(key,value)) ;
+         redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.expire(key,time));
+         return value;
+    }
+
+    public void expire(byte[] key,long time ) {
+        // 使用了lambda表达式
+        redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.expire(key,time));
+    }
 
+    public Long dbSize() {
+        // 使用了lambda表达式
+        return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.dbSize());
+    }
+
+    public Set<byte[]> keys(byte[] pattern) {
+        // 使用了lambda表达式
+        return redisTemplate.execute((RedisConnection redisConnection) -> redisConnection.keys(pattern));
+    }
     /** 
      * 普通缓存放入并设置时间 
      * @param key 键 

+ 0 - 47
src/main/java/com/bootdo/system/config/ShiroConfig.java

@@ -34,14 +34,6 @@ import java.util.List;
  */
 @Configuration
 public class ShiroConfig {
-    @Value("${spring.redis.host}")
-    private String host;
-    @Value("${spring.redis.password}")
-    private String password;
-    @Value("${spring.redis.port}")
-    private int port;
-    @Value("${spring.redis.timeout}")
-    private int timeout;
 
     @Value("${spring.cache.type}")
     private String cacheType ;
@@ -64,41 +56,6 @@ public class ShiroConfig {
         return new ShiroDialect();
     }
 
-    /*@Bean
-    ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
-        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
-        shiroFilterFactoryBean.setSecurityManager(securityManager);
-        shiroFilterFactoryBean.setLoginUrl("/login");
-        shiroFilterFactoryBean.setSuccessUrl("/index");
-        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
-        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
-        filterChainDefinitionMap.put("/login", "anon");
-        filterChainDefinitionMap.put("/code", "anon");
-        filterChainDefinitionMap.put("/sso/**", "anon");
-        filterChainDefinitionMap.put("/getVerify", "anon");
-        filterChainDefinitionMap.put("/css/**", "anon");
-        filterChainDefinitionMap.put("/js/**", "anon");
-        filterChainDefinitionMap.put("/fonts/**", "anon");
-        filterChainDefinitionMap.put("/img/**", "anon");
-        filterChainDefinitionMap.put("/docs/**", "anon");
-        filterChainDefinitionMap.put("/druid/**", "anon");
-        filterChainDefinitionMap.put("/upload/**", "anon");
-        filterChainDefinitionMap.put("/files/**", "anon");
-        filterChainDefinitionMap.put("/logout", "logout");
-        filterChainDefinitionMap.put("/", "anon");
-        filterChainDefinitionMap.put("/blog", "anon");
-        filterChainDefinitionMap.put("/blog/open/**", "anon");
-        filterChainDefinitionMap.put("/sms/**", "anon");
-        filterChainDefinitionMap.put("/**", "authc");
-        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
-
-        LinkedHashMap<String, Filter> filtersMap = new LinkedHashMap<>();
-
-        //配置自定义登出 覆盖 logout 之前默认的LogoutFilter
-        filtersMap.put("logout", shiroLogoutFilter());
-        shiroFilterFactoryBean.setFilters(filtersMap);
-        return shiroFilterFactoryBean;
-    }*/
 
     /**
      * Shiro的Web过滤器
@@ -210,11 +167,7 @@ public class ShiroConfig {
     @Bean
     public RedisManager redisManager() {
         RedisManager redisManager = new RedisManager();
-        redisManager.setHost(host);
-        redisManager.setPort(port);
         redisManager.setExpire(1800);// 配置缓存过期时间
-        //redisManager.setTimeout(1800);
-        redisManager.setPassword(password);
         return redisManager;
     }
 

+ 2 - 2
src/main/resources/application-prod.yml

@@ -54,8 +54,8 @@ spring:
       login-username: admin
       login-password: admin
   redis:
-    host: 172.18.105.10:7001,172.18.105.10:7002,172.18.105.10:7003,172.18.105.11:7004,172.18.105.11:7005,172.18.105.11:7006
-    port: 6379
+    cluster:
+      nodes: 172.18.105.10:7001,172.18.105.10:7002,172.18.105.10:7003,172.18.105.11:7004,172.18.105.11:7005,172.18.105.11:7006
     password: YXSA@2024
     # 连接超时时间(毫秒)
     timeout: 10000