Springboot2.x-統合Redis(Lettuce接続プール)


1.Redisのインストール
https://blog.csdn.net/W_Meng_H/article/details/100112360
2、Lettuce
Lettuceの接続はNettyに基づいており、接続インスタンス(StatefulRedisConnection)は複数のスレッド間で同時アクセス可能である.StatefulRedisConnectionはスレッドが安全であるため、1つの接続インスタンス(StatefulRedisConnection)はマルチスレッド環境での同時アクセスを満たすことができる.もちろんこれも伸縮可能な設計である.1つの接続インスタンスが不足している場合は、必要に応じて接続インスタンスを追加することもできます.
3、pom依存
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.apache.commons
            commons-pool2
        
        
	    com.alibaba
	    fastjson
	    1.2.35
        

4、application.propertiesプロファイル
#IP
spring.redis.host=
#  
spring.redis.port=
#  
spring.redis.password=
#       (  )
spring.redis.timeout=10000
# Redis      16   ,           ,   0
spring.redis.database=0
#         (          )    8
spring.redis.lettuce.pool.max-active=8
#            (          )    -1
spring.redis.lettuce.pool.max-wait=-1
#                8
spring.redis.lettuce.pool.max-idle=8
#                0
spring.redis.lettuce.pool.min-idle=0
#  
#spring.redis.cluster.nodes=IP:7001

5、Redis配置クラス
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        //    
        MyRedisSerializer myRedisSerializer = new MyRedisSerializer();
        //key     
        template.setKeySerializer(myRedisSerializer);
        //value   
        template.setValueSerializer(myRedisSerializer);
        //value hashmap   
        template.setHashValueSerializer(myRedisSerializer);
        return template;
    }

    static class MyRedisSerializer implements RedisSerializer {

        @Override
        public byte[] serialize(Object o) throws SerializationException {
            return serializeObj(o);
        }

        @Override
        public Object deserialize(byte[] bytes) throws SerializationException {
            return deserializeObj(bytes);
        }

        /**
         *    
         * @param object
         * @return
         */
        private static byte[] serializeObj(Object object) {
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] bytes = baos.toByteArray();
                return bytes;
            } catch (Exception e) {
                throw new RuntimeException("     !", e);
            }
        }

        /**
         *     
         * @param bytes
         * @return
         */
        private static Object deserializeObj(byte[] bytes) {
            if (bytes == null){
                return null;
            }
            ByteArrayInputStream bais = null;
            try {
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            } catch (Exception e) {
                throw new RuntimeException("      !", e);
            }
        }
    }
}    

カスタム設定:
    @Value("${spring.redis.cache.nodes}")
    private String nodes;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    private Integer maxIdle;
    @Value("${spring.redis.lettuce.pool.min-idle}")
    private Integer minIdle;
    @Value("${spring.redis.lettuce.pool.max-active}")
    private Integer maxTotal;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    private Long maxWaitMillis;

    @Bean
    LettuceConnectionFactory lettuceConnectionFactory() {
        //      
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(maxIdle == null ? 8 : maxIdle);
        poolConfig.setMinIdle(minIdle == null ? 1 : minIdle);
        poolConfig.setMaxTotal(maxTotal == null ? 8 : maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis == null ? 5000L : maxWaitMillis);
        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(poolConfig)
                .build();
        //   redis
        RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
        redisConfig.setHostName(host==null||"".equals(host)?"localhost":host.split(":")[0]);
        redisConfig.setPort(Integer.valueOf(host==null||"".equals(host)?"6379":host.split(":")[1]));
        if (password != null && !"".equals(password)) {
            redisConfig.setPassword(password);
        }

        //   redis
        // RedisSentinelConfiguration redisConfig = new RedisSentinelConfiguration();

        //   redis
        RedisClusterConfiguration redisConfig = new RedisClusterConfiguration();
        Set nodeses = new HashSet<>();
        String[] hostses = nodes.split("-");
        for (String h : hostses) {
            h = h.replaceAll("\\s", "").replaceAll("
", ""); if (!"".equals(h)) { String host = h.split(":")[0]; int port = Integer.valueOf(h.split(":")[1]); nodeses.add(new RedisNode(host, port)); } } redisConfig.setClusterNodes(nodeses); // redisConfig.setMaxRedirects(3); redisConfig.setPassword(password); return new LettuceConnectionFactory(redisConfig, lettucePoolingClientConfiguration); }

6、Redisツール類
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
    //=============================common============================  
    /** 
     *          
     * @param key   
     * @param time   ( ) 
     * @return 
     */  
    public boolean expire(String key,long time){  
        try {  
            if(time>0){  
                redisTemplate.expire(key, time, TimeUnit.SECONDS);  
            }  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *   key        
     * @param key      null 
     * @return   ( )   0        
     */  
    public long getExpire(String key){  
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);  
    }  

    /** 
     *   key     
     * @param key   
     * @return true    false    
     */  
    public boolean hasKey(String key){  
        try {  
            return redisTemplate.hasKey(key);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *      
     * @param key            
     */  
    @SuppressWarnings("unchecked")  
    public void del(String ... key){  
        if(key!=null&&key.length>0){  
            if(key.length==1){  
                redisTemplate.delete(key[0]);  
            }else{  
                redisTemplate.delete(CollectionUtils.arrayToList(key));  
            }  
        }  
    }  

    //============================String=============================  
    /** 
     *        
     * @param key   
     * @return   
     */  
    public Object get(String key){  
        return key==null?null:redisTemplate.opsForValue().get(key);  
    }  

    /** 
     *        
     * @param key   
     * @param value   
     * @return true   false   
     */  
    public boolean set(String key,Object value) {  
         try {  
            redisTemplate.opsForValue().set(key, value);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  

    }  

    /** 
     *             
     * @param key   
     * @param value   
     * @param time   ( ) time   0   time    0        
     * @return true   false    
     */  
    public boolean set(String key,Object value,long time){  
        try {  
            if(time>0){  
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);  
            }else{  
                set(key, value);  
            }  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *    
     * @param key   
     * @param by     (  0) 
     * @return 
     */  
    public long incr(String key, long delta){    
        if(delta<0){  
            throw new RuntimeException("        0");  
        }  
        return redisTemplate.opsForValue().increment(key, delta);  
    }  

    /** 
     *    
     * @param key   
     * @param by     (  0) 
     * @return 
     */  
    public long decr(String key, long delta){    
        if(delta<0){  
            throw new RuntimeException("        0");  
        }  
        return redisTemplate.opsForValue().increment(key, -delta);    
    }    

    //================================Map=================================  
    /** 
     * HashGet 
     * @param key      null 
     * @param item      null 
     * @return   
     */  
    public Object hget(String key,String item){  
        return redisTemplate.opsForHash().get(key, item);  
    }  

    /** 
     *   hashKey        
     * @param key   
     * @return         
     */  
    public Map hmget(String key){  
        return redisTemplate.opsForHash().entries(key);  
    }  

    /** 
     * HashSet 
     * @param key   
     * @param map        
     * @return true    false    
     */  
    public boolean hmset(String key, Map map){    
        try {  
            redisTemplate.opsForHash().putAll(key, map);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     * HashSet       
     * @param key   
     * @param map        
     * @param time   ( ) 
     * @return true   false   
     */  
    public boolean hmset(String key, Map map, long time){    
        try {  
            redisTemplate.opsForHash().putAll(key, map);  
            if(time>0){  
                expire(key, time);  
            }  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *    hash      ,         
     * @param key   
     * @param item   
     * @param value   
     * @return true    false   
     */  
    public boolean hset(String key,String item,Object value) {  
         try {  
            redisTemplate.opsForHash().put(key, item, value);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *    hash      ,         
     * @param key   
     * @param item   
     * @param value   
     * @param time   ( )    :      hash    ,            
     * @return true    false   
     */  
    public boolean hset(String key,String item,Object value,long time) {  
         try {  
            redisTemplate.opsForHash().put(key, item, value);  
            if(time>0){  
                expire(key, time);  
            }  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *   hash     
     * @param key      null 
     * @param item            null 
     */  
    public void hdel(String key, Object... item){    
        redisTemplate.opsForHash().delete(key,item);  
    }   

    /** 
     *   hash          
     * @param key      null 
     * @param item      null 
     * @return true    false    
     */  
    public boolean hHasKey(String key, String item){  
        return redisTemplate.opsForHash().hasKey(key, item);  
    }   

    /** 
     * hash        ,                 
     * @param key   
     * @param item   
     * @param by     (  0) 
     * @return 
     */  
    public double hincr(String key, String item,double by){    
        return redisTemplate.opsForHash().increment(key, item, by);  
    }  

    /** 
     * hash   
     * @param key   
     * @param item   
     * @param by     (  0) 
     * @return 
     */  
    public double hdecr(String key, String item,double by){    
        return redisTemplate.opsForHash().increment(key, item,-by);    
    }    

    //============================set=============================  
    /** 
     *   key  Set      
     * @param key   
     * @return 
     */  
    public Set sGet(String key){  
        try {  
            return redisTemplate.opsForSet().members(key);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  

    /** 
     *   value   set   ,     
     * @param key   
     * @param value   
     * @return true    false    
     */  
    public boolean sHasKey(String key,Object value){  
        try {  
            return redisTemplate.opsForSet().isMember(key, value);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *      set   
     * @param key   
     * @param values         
     * @return      
     */  
    public long sSet(String key, Object...values) {  
        try {  
            return redisTemplate.opsForSet().add(key, values);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  

    /** 
     *  set       
     * @param key   
     * @param time   ( ) 
     * @param values         
     * @return      
     */  
    public long sSetAndTime(String key,long time,Object...values) {  
        try {  
            Long count = redisTemplate.opsForSet().add(key, values);  
            if(time>0) expire(key, time);  
            return count;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  

    /** 
     *   set      
     * @param key   
     * @return 
     */  
    public long sGetSetSize(String key){  
        try {  
            return redisTemplate.opsForSet().size(key);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  

    /** 
     *     value  
     * @param key   
     * @param values         
     * @return       
     */  
    public long setRemove(String key, Object ...values) {  
        try {  
            Long count = redisTemplate.opsForSet().remove(key, values);  
            return count;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  
    //===============================list=================================  

    /** 
     *   list      
     * @param key   
     * @param start    
     * @param end     0   -1      
     * @return 
     */  
    public List lGet(String key,long start, long end){  
        try {  
            return redisTemplate.opsForList().range(key, start, end);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  

    /** 
     *   list      
     * @param key   
     * @return 
     */  
    public long lGetListSize(String key){  
        try {  
            return redisTemplate.opsForList().size(key);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  

    /** 
     *        list    
     * @param key   
     * @param index     index>=0 , 0   ,1      ,    ;index<0 ,-1,  ,-2       ,     
     * @return 
     */  
    public Object lGetIndex(String key,long index){  
        try {  
            return redisTemplate.opsForList().index(key, index);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  

    /** 
     *  list     
     * @param key   
     * @param value   
     * @param time   ( ) 
     * @return 
     */  
    public boolean lSet(String key, Object value) {  
        try {  
            redisTemplate.opsForList().rightPush(key, value);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *  list     
     * @param key   
     * @param value   
     * @param time   ( ) 
     * @return 
     */  
    public boolean lSet(String key, Object value, long time) {  
        try {  
            redisTemplate.opsForList().rightPush(key, value);  
            if (time > 0) expire(key, time);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *  list     
     * @param key   
     * @param value   
     * @param time   ( ) 
     * @return 
     */  
    public boolean lSet(String key, List value) {  
        try {  
            redisTemplate.opsForList().rightPushAll(key, value);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *  list     
     * @param key   
     * @param value   
     * @param time   ( ) 
     * @return 
     */  
    public boolean lSet(String key, List value, long time) {  
        try {  
            redisTemplate.opsForList().rightPushAll(key, value);  
            if (time > 0) expire(key, time);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }  

    /** 
     *       list       
     * @param key   
     * @param index    
     * @param value   
     * @return 
     */  
    public boolean lUpdateIndex(String key, long index,Object value) {  
        try {  
            redisTemplate.opsForList().set(key, index, value);  
            return true;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
    }   

    /** 
     *   N   value  
     * @param key   
     * @param count       
     * @param value   
     * @return       
     */  
    public long lRemove(String key,long count,Object value) {  
        try {  
            Long remove = redisTemplate.opsForList().remove(key, count, value);  
            return remove;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 0;  
        }  
    }  
}