zoukankan      html  css  js  c++  java
  • SpringBoot2.x中redis使用(lettuce)

    java代码操作Redis,需要使用Jedis,也就是redis支持java的第三方类库 注意:Jedis2.7以上的版本才支持集群操作

    maven配置

    新建SpringBoot2.0.3的WEB工程,在MAVEN的pom.xml文件中加入如下依赖

    <dependencies>     
            <!--默认是lettuce客户端-->      
            <dependency>           
                <groupId>org.springframework.boot</groupId>            
                <artifactId>spring-boot-starter-data-redis</artifactId>        
            </dependency>
    
            <!-- redis依赖commons-pool 这个依赖一定要添加 -->        
            <dependency>           
                <groupId>org.apache.commons</groupId>            
                <artifactId>commons-pool2</artifactId>  
                     
            </dependency>
            <!-- 测试库依赖 -->        
            <dependency>           
                <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-test</artifactId>            
                <scope>test</scope>        
            </dependency>
             
        </dependencies>

    配置文件配置 

    spring:
      redis:  
        port: 6379
        password: 123456  
        host: 192.168.20.135    
        lettuce:      
          pool:        
            max-active: 8 # 连接池大连接数(使用负值表示没有限制)        
            max-idle: 8 # 连接池中的大空闲连接        
            min-idle: 0 # 连接池中的小空闲连接        
            max-wait: 1000 # 连接池大阻塞等待时间(使用负值表示没有限制)      
            shutdown-timeout: 100   # 关闭超时时间

    redis配置类

    JdbcTemplate-->JDBC 进一步封装。 RedisTemplate-->redis进行了进一步封装 (lettuce)

    简介

    编写缓存配置类RedisConfig用于调优缓存默认配置,RedisTemplate<String, Object>的类型兼容性更高
    大家可以看到在redisTemplate()这个方法中用JacksonJsonRedisSerializer更换掉了Redis默认的序列化方 式:JdkSerializationRedisSerializer spring-data-redis中序列化类有以下几个:
    GenericToStringSerializer:可以将任何对象泛化为字符创并序列化 Jackson2JsonRedisSerializer:序列化 Object对象为json字符创(与JacksonJsonRedisSerializer相同) JdkSerializationRedisSerializer:序列化java 对象 StringRedisSerializer:简单的字符串序列化 JdkSerializationRedisSerializer序列化被序列化对象必须实现Serializable接口,被序列化除属性内容还有其他 内容,长度长且不易阅读,默认就是采用这种序列化方式
    存储内容如下:
    "xacxedx00x05srx00!com.oreilly.springdata.redis.Userxb1x1c xcdxed%xd8x02x00x02Ix00x03ageLx00userNametx00x12Ljava/lang/String;xpx00x00x00 x14tx00x05user1"
               <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>  </dependencies>
    spring: redis:   port: 6379   password: guoweixin   host: 192.168.20.135   lettuce:     pool:       max-active: 8 # 连接池大连接数(使用负值表示没有限制)       max-idle: 8 # 连接池中的大空闲连接       min-idle: 0 # 连接池中的小空闲连接       max-wait: 1000 # 连接池大阻塞等待时间(使用负值表示没有限制)     shutdown-timeout: 100   # 关闭超时时间
    JacksonJsonRedisSerializer序列化,被序列化对象不需要实现Serializable接口,被序列化的结果清晰,容易阅 读,而且存储字节少,速度快
    存储内容如下:
    "{"userName":"guoweixin","age":20}" StringRedisSerializer序列化
    一般如果key、value都是string字符串的话,就是用这个就可以了

    RedisConfig 类

     1 package com.xq.redis;
     2 
     3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
     4 import com.fasterxml.jackson.annotation.PropertyAccessor;
     5 import com.fasterxml.jackson.databind.ObjectMapper;
     6 import org.springframework.cache.CacheManager;
     7 import org.springframework.cache.annotation.CachingConfigurerSupport;
     8 import org.springframework.cache.interceptor.KeyGenerator;
     9 import org.springframework.context.annotation.Bean;
    10 import org.springframework.context.annotation.Configuration;
    11 import org.springframework.data.redis.cache.RedisCacheConfiguration;
    12 import org.springframework.data.redis.cache.RedisCacheManager;
    13 import org.springframework.data.redis.cache.RedisCacheWriter;
    14 import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    15 import org.springframework.data.redis.core.RedisTemplate;
    16 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    17 import org.springframework.data.redis.serializer.StringRedisSerializer;
    18 
    19 import java.lang.reflect.Method;
    20 
    21 @Configuration
    22 public class RedisConfig extends CachingConfigurerSupport {
    23     /**
    24      * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过Spring 的依赖注入特性进行自定义的 配置注入并且此类是一个配置类可以更多程度的自定义配置    
    25      *
    26      * @return
    27      */
    28     @Bean
    29     @Override
    30     public KeyGenerator keyGenerator() {
    31         return new KeyGenerator() {
    32             @Override
    33             public Object generate(Object target, Method method, Object... params) {
    34                 StringBuilder sb = new StringBuilder();
    35                 sb.append(target.getClass().getName());
    36                 sb.append(method.getName());
    37                 for (Object obj : params) {
    38                     sb.append(obj.toString());
    39                 }
    40                 return sb.toString();
    41             }
    42         };
    43     }
    44 
    45     /**
    46      *    
    47      * 缓存配置管理器
    48      */
    49     @Bean
    50     public CacheManager cacheManager(LettuceConnectionFactory factory) {
    51         //以锁写入的方式创建RedisCacheWriter对象        
    52         RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
    53         //创建默认缓存配置对象      
    54         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    55         RedisCacheManager cacheManager = new RedisCacheManager(writer, config);
    56         return cacheManager;
    57     }
    58 
    59     @Bean
    60     public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
    61         RedisTemplate<String, Object> template = new RedisTemplate<>();
    62         template.setConnectionFactory(factory);
    63         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    64         ObjectMapper om = new ObjectMapper();
    65         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    66         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    67         jackson2JsonRedisSerializer.setObjectMapper(om);
    68         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    69         // 在使用注解@Bean返回RedisTemplate的时候,同时配置hashKey与hashValue的序列化方式。        
    70         // key采用String的序列化方式        
    71         template.setKeySerializer(stringRedisSerializer);
    72         // value序列化方式采用jackson        
    73         template.setValueSerializer(jackson2JsonRedisSerializer);
    74         // hash的key也采用String的序列化方式        
    75         template.setHashKeySerializer(stringRedisSerializer);
    76         // hash的value序列化方式采用jackson        
    77         template.setHashValueSerializer(jackson2JsonRedisSerializer);
    78         template.afterPropertiesSet();
    79         return template;
    80     }
    81 }
    RedisConfig 

     代码示例

    测试String 类型

    package com.xq.serviceImpl;
    
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;
    
    import java.util.concurrent.TimeUnit;
    
    @Service
    public class RedisServiceImpl {
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        private static org.apache.log4j.Logger log = Logger.getLogger(RedisServiceImpl.class);
    
        /**
         * 普通缓存放入  
         *
         * @param key 键    
         * @return true成功 false失败    
         */
        public String getString(String key) {
            if (redisTemplate.hasKey(key)) {
                log.info("Redis中查询");
                return (String) redisTemplate.opsForValue().get(key);
            } else {
                String val = "lcoil";
                redisTemplate.opsForValue().set(key, val);
                log.info("数据库中查询的");
                return val;
            }
        }
    
        /**
         * 普通缓存放入    
         *
         * @param value      值    
         * @param expireTime 超时时间(秒)    
         * @return true成功 false失败    
         */
        public Boolean set(String key, Object value, int expireTime) {
            try {
                redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }
    RedisServiceImpl

    测试Hash类型 

     1 package com.xq.serviceImpl.hash;
     2 
     3 import com.xq.model.User;
     4 import org.apache.log4j.Logger;
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.data.redis.core.HashOperations;
     7 import org.springframework.data.redis.core.RedisTemplate;
     8 import org.springframework.stereotype.Service;
     9 
    10 import javax.annotation.Resource;
    11 
    12 @Service
    13 public class RedisServiceImpl {
    14     @Autowired
    15     private RedisTemplate<String, Object> redisTemplate;
    16     @Resource(name = "redisTemplate")
    17     private HashOperations<String, String, User> hash;
    18 
    19     private static org.apache.log4j.Logger log = Logger.getLogger(RedisServiceImpl.class);
    20 
    21     /**
    22      * 判断key是否存在,如果存在 在Redis中查询    
    23      * 如果不存在,在MYSQL中查询,并将结果得到,添加到Redis Hash中    
    24      *
    25      * @param id    
    26      * @return    
    27      */
    28     public User selectUserById1(String id) {
    29         if (hash.hasKey("user", id)) {
    30             log.info("Redis中查询对象");
    31             return
    32                     hash.get("user", id);
    33         } else {
    34             User u = new User();
    35             u.setId(id);
    36             u.setName("coil");
    37             u.setAge(22);
    38             log.info("mysql中查询对象");
    39             hash.put("user", id, u);
    40             return u;
    41         }
    42     }
    43 }
    RedisServiceImpl

    hash类型代码示例

      1 package com.xq.serviceImpl.hash;
      2 
      3 import com.xq.service.HashCacheService;
      4 import org.slf4j.Logger;
      5 import org.slf4j.LoggerFactory;
      6 import org.springframework.beans.factory.annotation.Autowired;
      7 import org.springframework.data.redis.core.Cursor;
      8 import org.springframework.data.redis.core.RedisTemplate;
      9 import org.springframework.data.redis.core.ScanOptions;
     10 import org.springframework.stereotype.Service;
     11 import org.springframework.util.CollectionUtils;
     12 
     13 import java.util.List;
     14 import java.util.Map;
     15 import java.util.Set;
     16 import java.util.concurrent.TimeUnit;
     17 
     18 @Service("hashCacheService")
     19 public class HashCacheServiceImpl implements HashCacheService {
     20     private final static Logger log = LoggerFactory.getLogger(HashCacheServiceImpl.class);
     21     @Autowired
     22     private RedisTemplate<String, Object> redisTemplate;
     23 
     24     /**
     25      * 获取MAP中的某个值    
     26      *
     27      * @param key  键    
     28      * @param item 项    
     29      * @return 值    
     30      */
     31     public Object hget(String key, String item) {
     32         return redisTemplate.opsForHash().get(key, item);
     33     }
     34 
     35     /**
     36      * 获取hashKey对应的所有键值    
     37      *
     38      * @param key 键    
     39      * @return 对应的多个键值    
     40      */
     41     public Map<Object, Object> hmget(String key) {
     42         return redisTemplate.opsForHash().entries(key);
     43     }
     44 
     45     /**
     46      * 以map集合的形式添加键值对    
     47      *
     48      * @param key 键    
     49      * @param map 对应多个键值    
     50      * @return true 成功 false 失败    
     51      */
     52     public boolean hmset(String key, Map<String, Object> map) {
     53         try {
     54             redisTemplate.opsForHash().putAll(key, map);
     55             return true;
     56         } catch (Exception e) {
     57             e.printStackTrace();
     58             return false;
     59         }
     60     }
     61 
     62     /**
     63      * HashSet 并设置时间    
     64      *
     65      * @param key  键    
     66      * @param map  对应多个键值    
     67      * @param time 时间(秒)    
     68      * @return true成功 false失败    
     69      */
     70     public boolean hmset(String key, Map<String, Object> map, long time) {
     71         try {
     72             redisTemplate.opsForHash().putAll(key, map);
     73             if (time > 0) {
     74                 expire(key, time);
     75             }
     76             return true;
     77         } catch (Exception e) {
     78             e.printStackTrace();
     79             return false;
     80         }
     81     }
     82 
     83     /**
     84      * 向一张hash表中放入数据,如果不存在将创建    
     85      *
     86      * @param key     键    
     87      * @param item  项    
     88      * @param value 值    
     89      * @return true 成功 false失败    
     90      */
     91     public boolean hset(String key, String item, Object value) {
     92         try {
     93             redisTemplate.opsForHash().put(key, item, value);
     94             return true;
     95         } catch (Exception e) {
     96             e.printStackTrace();
     97             return false;
     98         }
     99     }
    100 
    101     /**
    102      * 向一张hash表中放入数据,如果不存在将创建    
    103      *
    104      * @param key     键    
    105      * @param item  项    
    106      * @param value 值    
    107      * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间    
    108      * @return true 成功 false失败    
    109      */
    110     public boolean hset(String key, String item, Object value, long time) {
    111         try {
    112             redisTemplate.opsForHash().put(key, item, value);
    113             if (time > 0) {
    114                 expire(key, time);
    115             }
    116             return true;
    117         } catch (Exception e) {
    118             e.printStackTrace();
    119             return false;
    120         }
    121     }
    122 
    123     /**
    124      * 删除hash表中的值    
    125      *
    126      * @param key  键 不能为null    
    127      * @param item 项 可以使多个 不能为null    
    128      */
    129     public void hdel(String key, Object... item) {
    130 
    131         redisTemplate.opsForHash().delete(key, item);
    132     }
    133 
    134     /**
    135      * 判断hash表中是否有该项的值    
    136      *
    137      * @param key  键 不能为null    
    138      * @param item 项 不能为null    
    139      * @return true 存在 false不存在    
    140      */
    141     public boolean hHasKey(String key, String item) {
    142         return redisTemplate.opsForHash().hasKey(key, item);
    143     }
    144 
    145     /**
    146      * hash递增 如果不存在,就会创建一个 并把新增后的值返回    
    147      *
    148      * @param key  键    
    149      * @param item 项    
    150      * @param by     要增加几(大于0)    
    151      * @return    
    152      */
    153     public long hincr(String key, String item, long by) {
    154         return redisTemplate.opsForHash().increment(key, item, by);
    155     }
    156 
    157     /**
    158      * hash递减    
    159      *
    160      * @param key  键    
    161      * @param item 项    
    162      * @param by     要减少记(小于0)    
    163      * @return    
    164      */
    165     public long hdecr(String key, String item, long by) {
    166         return redisTemplate.opsForHash().increment(key, item, -by);
    167     }
    168 
    169     /**
    170      *    
    171      * 获取指定变量中的hashMap值。    
    172      *
    173      * @param key    
    174      * @return 返回LIST对象    
    175      */
    176     @Override
    177     public List<Object> values(String key) {
    178         return redisTemplate.opsForHash().values(key);
    179     }
    180 
    181     /**
    182      * 获取变量中的键。    
    183      *
    184      * @param key    
    185      * @return 返回SET集合    
    186      */
    187     @Override
    188     public Set<Object> keys(String key) {
    189         return redisTemplate.opsForHash().keys(key);
    190     }
    191 
    192     /**
    193      * 获取变量的长度。    
    194      *
    195      * @param key 键    
    196      * @return 返回长度    
    197      */
    198     @Override
    199     public long size(String key) {
    200         return redisTemplate.opsForHash().size(key);
    201     }
    202 
    203     /**
    204      * 以集合的方式获取变量中的值。    
    205      *
    206      * @param key     
    207      * @param list    
    208      * @return 返回LIST集合值    
    209      */
    210     @Override
    211     public List multiGet(String key, List list) {
    212         return redisTemplate.opsForHash().multiGet(key, list);
    213     }
    214 
    215     /**
    216      * 如果变量值存在,在变量中可以添加不存在的的键值对    
    217      * 如果变量不存在,则新增一个变量,同时将键值对添加到该变量。    
    218      *
    219      * @param key        
    220      * @param hashKey    
    221      * @param value      
    222      */
    223     @Override
    224     public void putIfAbsent(String key, String hashKey, Object value) {
    225         redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
    226     }
    227 
    228     /**
    229      * 匹配获取键值对,ScanOptions.NONE为获取全部键对, ScanOptions.scanOptions().match("map1").build()    
    230      * 匹配获取键位map1的键值对,不能模糊匹配。    
    231      *
    232      * @param key        
    233      * @param options    
    234      * @return    
    235      */
    236     @Override
    237     public Cursor<Map.Entry<Object, Object>> scan(String key, ScanOptions options) {
    238         return redisTemplate.opsForHash().scan(key, options);
    239     }
    240 
    241     /**
    242      * 删除变量中的键值对,可以传入多个参数,删除多个键值对。    
    243      *
    244      * @param key      键    
    245      * @param hashKeys MAP中的KEY    
    246      */
    247     @Override
    248     public void delete(String key, String... hashKeys) {
    249         redisTemplate.opsForHash().delete(key, hashKeys);
    250     }
    251 
    252     public boolean expire(String key, long seconds) {
    253         return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    254     }
    255 
    256     /**
    257      * 删除    
    258      *
    259      * @param keys    
    260      */
    261     @Override
    262     public void del(String... keys) {
    263         if (keys != null && keys.length > 0) {
    264 
    265             if (keys.length == 1) {
    266                 redisTemplate.delete(keys[0]);
    267             } else {
    268 
    269                 redisTemplate.delete(CollectionUtils.arrayToList(keys));
    270             }
    271         }
    272     }
    273 
    274     @Override
    275     public long getExpire(String key) {
    276         return 0;
    277     }
    278 }
    HashCacheServiceImpl

     List 类型代码示例

      1 package com.xq.serviceImpl.list;
      2 
      3 import com.xq.service.ListCacheService;
      4 import org.slf4j.Logger;
      5 import org.slf4j.LoggerFactory;
      6 import org.springframework.beans.factory.annotation.Autowired;
      7 import org.springframework.data.redis.core.RedisTemplate;
      8 import org.springframework.stereotype.Service;
      9 import org.springframework.util.CollectionUtils;
     10 
     11 import java.util.List;
     12 import java.util.concurrent.TimeUnit;
     13 
     14 @Service("listCacheService")
     15 public class ListCacheServiceImpl implements ListCacheService {
     16     private final static Logger log = LoggerFactory.getLogger(ListCacheServiceImpl.class);
     17     @Autowired
     18     private RedisTemplate<String, Object> redisTemplate;
     19 
     20     /**
     21      * 将list放入缓存    
     22      *
     23      * @param key     键    
     24      * @param value 值    
     25      * @return true 成功 false 失败    
     26      */
     27     public boolean lpushAll(String key, List<Object> value) {
     28         try {
     29             redisTemplate.opsForList().leftPushAll(key, value);
     30             return true;
     31         } catch (Exception e) {
     32             e.printStackTrace();
     33             return false;
     34         }
     35     }
     36 
     37     /**
     38      * 将list放入缓存    
     39      *
     40      * @param key     键    
     41      * @param value 值    
     42      * @param time  时间(秒)    
     43      * @return true 成功 false 失败    
     44      */
     45     public boolean lpushAll(String key, List<Object> value, long time) {
     46         Boolean flag = false;
     47         try {
     48             redisTemplate.opsForList().leftPushAll(key, value);
     49             if (time > 0) {
     50                 expire(key, time);
     51                 flag = true;
     52             }
     53         } catch (Exception e) {
     54             e.printStackTrace();
     55             flag = false;
     56         }
     57         return flag;
     58     }
     59 
     60     /**
     61      * 将list放入缓存    
     62      *
     63      * @param key     键    
     64      * @param value 值    
     65      * @return true 成功 false 失败    
     66      */
     67     public boolean rpushAll(String key, List<Object> value) {
     68         try {
     69             redisTemplate.opsForList().rightPushAll(key, value);
     70             return true;
     71         } catch (Exception e) {
     72             e.printStackTrace();
     73             return false;
     74         }
     75     }
     76 
     77     /**
     78      *    
     79      * 将list放入缓存    
     80      *
     81      * @param key     键    
     82      * @param value 值    
     83      * @param time  时间(秒)    
     84      * @return true 成功 false 失败    
     85      */
     86     public boolean rpushAll(String key, List<Object> value, long time) {
     87         try {
     88             redisTemplate.opsForList().rightPushAll(key, value);
     89             if (time > 0)
     90                 expire(key, time);
     91             return true;
     92         } catch (Exception e) {
     93             e.printStackTrace();
     94             return false;
     95         }
     96     }
     97 
     98     /**
     99      * 在变量左边添加元素值。    
    100      *
    101      * @param key    键    
    102      * @param object 值    
    103      * @return true 成功 false 失败    
    104      */
    105     @Override
    106     public Boolean lpush(String key, Object object) {
    107         try {
    108             redisTemplate.opsForList().leftPush(key, object);
    109             return true;
    110         } catch (Exception e) {
    111             e.printStackTrace();
    112             return false;
    113         }
    114     }
    115 
    116     /**
    117      * 把最后一个参数值放到指定集合的第一个出现中间参数的前面,如果中间参数值存在的话。    
    118      *
    119      * @param key    键    
    120      * @param pivot  中间参数    
    121      * @param object 要放的值    
    122      * @return 成功 true 失败 false    
    123      */
    124     @Override
    125     public Boolean lpush(String key, Object pivot, Object object) {
    126         try {
    127             redisTemplate.opsForList().leftPush(key, pivot, object);
    128             return true;
    129         } catch (Exception e) {
    130             e.printStackTrace();
    131             return false;
    132         }
    133     }
    134 
    135     /**
    136      * 集合中第一次出现第二个参数变量元素的右边添加第三个参数变量的元素值。    
    137      *
    138      * @param key    键    
    139      * @param pivot  中间参数    
    140      * @param object 要放的值    
    141      * @return 成功 true 失败 false    
    142      */
    143     @Override
    144     public Boolean rpush(String key, Object pivot, Object object) {
    145         try {
    146             redisTemplate.opsForList().rightPush(key, pivot, object);
    147             return true;
    148         } catch (Exception e) {
    149             e.printStackTrace();
    150             return false;
    151         }
    152     }
    153 
    154     /**
    155      * 向集合最右边添加元素。    
    156      *
    157      * @param key    键    
    158      * @param object 值    
    159      * @return 成功 true 失败 false    
    160      */
    161 
    162     @Override
    163     public Boolean rpush(String key, Object object) {
    164         try {
    165             redisTemplate.opsForList().rightPush(key, object);
    166             return true;
    167         } catch (Exception e) {
    168             e.printStackTrace();
    169             return false;
    170         }
    171     }
    172 
    173     /**
    174      * 在变量左边添加元素值。    
    175      *
    176      * @param key        键    
    177      * @param expireTime 超时时间    
    178      * @param objects    值    
    179      * @return 成功 true 失败 false    
    180      */
    181     @Override
    182     public Boolean lpush(String key, int expireTime, Object... objects) {
    183         boolean flag = false;
    184         try {
    185             redisTemplate.opsForList().leftPush(key, objects);
    186             if (expireTime > 0) {
    187                 expire(key, expireTime);
    188                 flag = true;
    189             }
    190 
    191         } catch (Exception e) {
    192             e.printStackTrace();
    193             flag = false;
    194         } finally {
    195             return flag;
    196         }
    197     }
    198 
    199     /**
    200      * 在变量右边添加元素值。    
    201      *
    202      * @param key        键    
    203      * @param expireTime 超时时间    
    204      * @param objects    值    
    205      * @return 成功 true 失败 false    
    206      */
    207     @Override
    208     public Boolean rpush(String key, int expireTime, Object... objects) {
    209         boolean flag = false;
    210         try {
    211             redisTemplate.opsForList().rightPush(key, objects);
    212             if (expireTime > 0) {
    213                 expire(key, expireTime);
    214                 flag = true;
    215             }
    216         } catch (Exception e) {
    217             e.printStackTrace();
    218             flag = false;
    219         } finally {
    220             return flag;
    221         }
    222     }
    223 
    224     /**
    225      * 如果存在集合则向左边添加元素,不存在不加    
    226      *
    227      * @param key    键    
    228      * @param object 值    
    229      * @return 成功 true 失败 false    
    230      */
    231     @Override
    232     public boolean lPushIfPresent(String key, Object object) {
    233         try {
    234             redisTemplate.opsForList().leftPushIfPresent(key, object);
    235             return true;
    236         } catch (Exception e) {
    237             e.printStackTrace();
    238             return false;
    239         }
    240     }
    241 
    242     /**
    243      * 如果存在集合则向右边添加元素,不存在不加    
    244      *
    245      * @param key    键    
    246      * @param object 返回    
    247      * @return 成功 true 失败 false    
    248      */
    249     @Override
    250     public boolean rPushIfPresent(String key, Object object) {
    251         try {
    252             redisTemplate.opsForList().rightPushIfPresent(key, object);
    253             return true;
    254         } catch (Exception e) {
    255             e.printStackTrace();
    256             return false;
    257         }
    258     }
    259 
    260     /**
    261      * 移除集合中的左边第一个元素    
    262      *
    263      * @param key 键    
    264      * @return 返回右边的第一个元素    
    265      */
    266     @Override
    267     public Object lpop(String key) {
    268         return redisTemplate.opsForList().leftPop(key);
    269     }
    270 
    271     /**
    272      * 移除集合中右边的元素。一般用在队列取值    
    273      *
    274      * @param key 键    
    275      * @return 返回右边的元素    
    276      */
    277     @Override
    278     public Object rpop(String key) {
    279         return redisTemplate.opsForList().rightPop(key);
    280     }
    281 
    282     /**
    283      * 移除集合中左边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。一般用在队列取值    
    284      *
    285      * @param key  键    
    286      * @param time 时间    
    287      * @return 左边的元素    
    288      */
    289     @Override
    290     public Object lpop(String key, long time) {
    291         return redisTemplate.opsForList().leftPop(key, time, TimeUnit.MILLISECONDS);
    292     }
    293 
    294     /**
    295      * 移除集合中右边的元素在等待的时间里,如果超过等待的时间仍没有元素则退出。一般用在队列取值    
    296      *
    297      * @param key  键    
    298      * @param time 时间    
    299      * @return 返回右边元素    
    300      */
    301     @Override
    302     public Object rpop(String key, long time) {
    303         return redisTemplate.opsForList().rightPop(key, time, TimeUnit.MILLISECONDS);
    304     }
    305 
    306     /**
    307      * 获取指定区间的值。    
    308      *
    309      * @param key   键    
    310      * @param start 开始位置    
    311      * @param end     结束位置,为-1指结尾的位置, start 0,end -1取所有    
    312      * @return    
    313      */
    314     @Override
    315     public List<Object> lrange(String key, long start, long end) {
    316         return redisTemplate.opsForList().range(key, start, end);
    317     }
    318 
    319     /**
    320      * 获取集合长度    
    321      *
    322      * @param key 键    
    323      * @return 返回长度    
    324      */
    325     @Override
    326     public Long llen(String key) {
    327         return redisTemplate.opsForList().size(key);
    328     }
    329 
    330     /**
    331      * 在集合的指定位置插入元素,如果指定位置已有元素,则覆盖,没有则新增,超过集合下标+n则会报错。    
    332      *
    333      * @param key   键    
    334      * @param index 位置    
    335      * @param value 值    
    336      */
    337     @Override
    338     public void set(String key, Long index, Object value) {
    339         redisTemplate.opsForList().set(key, index, value);
    340     }
    341 
    342     /**
    343      * 获取集合指定位置的值    
    344      *
    345      * @param key   键    
    346      * @param index 位置    
    347      * @return 返回值    
    348      */
    349     @Override
    350     public Object lindex(String key, Long index) {
    351         return redisTemplate.opsForList().index(key, index);
    352     }
    353 
    354     /**
    355      * 从存储在键中的列表中删除等于值的元素的第一个计数事件。count> 0:    
    356      * 删除等于从左到右移动的值的第一个元素;count< 0:删除等于从右到左移动的值的第一个元素;count = 0:删除等于value的所有元素。    
    357      *
    358      * @param key    键    
    359      * @param count     
    360      * @param object    
    361      * @return    
    362      */
    363     @Override
    364     public long remove(String key, long count, Object object) {
    365         return redisTemplate.opsForList().remove(key, count, object);
    366     }
    367 
    368     /**
    369      * 截取集合元素长度,保留长度内的数据。    
    370      *
    371      * @param key   键    
    372      * @param start 开始位置    
    373      * @param end     结束位置    
    374      */
    375     @Override
    376     public void trim(String key, long start, long end) {
    377         redisTemplate.opsForList().trim(key, start, end);
    378     }
    379 
    380     /**
    381      * 除集合中右边的元素,同时在左边加入一个元素。    
    382      *
    383      * @param key 键    
    384      * @param str 加入的元素    
    385      * @return 返回右边的元素    
    386      */
    387     @Override
    388     public Object rightPopAndLeftPush(String key, String str) {
    389         return redisTemplate.opsForList().rightPopAndLeftPush(key, str);
    390     }
    391 
    392     /**
    393      * 移除集合中右边的元素在等待的时间里,同时在左边添加元素,如果超过等待的时间仍没有元素则退出。    
    394      *
    395      * @param key     键    
    396      * @param str     左边增中的值    
    397      * @param timeout 超时时间    
    398      * @return 返回移除右边的元素    
    399      */
    400     @Override
    401     public Object rightPopAndLeftPush(String key, String str, long timeout) {
    402         return redisTemplate.opsForList().rightPopAndLeftPush(key, str, timeout, TimeUnit.MILLISECONDS);
    403     }
    404 
    405     /**
    406      * 删除
    407      *   应用场景
    408      * 项目常应用于:1、对数据量大的集合数据删减
    409      * 2、任务队列
    410      * 1、对数据量大的集合数据删减 列表数据显示、关注列表、粉丝列表、留言评价等…分页、热点新闻(Top5)等 利用 LRANGE还可以很方便的实现分页的功能,在博客系统中,每片博文的评论也可以存入一个单独的list中。
    411      * 2、任务队列 (list通常用来实现一个消息队列,而且可以确保先后顺序,不必像MySQL那样还需要通过ORDER BY来 进行排序)
    412      *   代码案例 案例1
    413      *     * @param keys 键    
    414      */
    415     @Override
    416     public void del(String... keys) {
    417         if (keys != null && keys.length > 0) {
    418             if (keys.length == 1) {
    419                 redisTemplate.delete(keys[0]);
    420             } else {
    421                 redisTemplate.delete(CollectionUtils.arrayToList(keys));
    422             }
    423         }
    424     }
    425 
    426     /**
    427      *    
    428      * 设置过期时间    
    429      *
    430      * @param key     键    
    431      * @param seconds 超时时间    
    432      * @return 成功 true 失败 false    
    433      **/
    434     @Override
    435     public boolean expire(String key, long seconds) {
    436         return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    437     }
    438 }
    ListCacheServiceImpl

     Set 类型代码示例

      1 package com.xq.serviceImpl.set;
      2 
      3 import com.xq.service.SetCacheService;
      4 import org.slf4j.Logger;
      5 import org.slf4j.LoggerFactory;
      6 import org.springframework.beans.factory.annotation.Autowired;
      7 import org.springframework.data.redis.core.Cursor;
      8 import org.springframework.data.redis.core.RedisTemplate;
      9 import org.springframework.data.redis.core.ScanOptions;
     10 import org.springframework.stereotype.Service;
     11 import org.springframework.util.CollectionUtils;
     12 
     13 import java.util.List;
     14 import java.util.Set;
     15 import java.util.concurrent.TimeUnit;
     16 
     17 @Service("setCacheService")
     18 public class SetCacheServiceImpl implements SetCacheService {
     19     private final static Logger log = LoggerFactory.getLogger(SetCacheServiceImpl.class);
     20     @Autowired
     21     private RedisTemplate<String, Object> redisTemplate;
     22 
     23     /**
     24      * 向变量中批量添加值。    
     25      *
     26      * @param key     键    
     27      * @param objects 值    
     28      * @return true成功 false失败    
     29      */
     30     @Override
     31     public boolean add(String key, Object... objects) {
     32         try {
     33             redisTemplate.opsForSet().add(key, objects);
     34             return true;
     35         } catch (Exception e) {
     36             e.printStackTrace();
     37             return false;
     38         }
     39     }
     40 
     41     /**
     42      * 向变量中批量添加值。    
     43      *
     44      * @param key        键    
     45      * @param expireTime 值    
     46      * @param values     值    
     47      * @return true成功 false失败  
     48      */
     49     @Override
     50     public Boolean add(String key, int expireTime, Object... values) {
     51         try {
     52             redisTemplate.opsForSet().add(key, values);
     53             if (expireTime > 0)
     54                 expire(key, expireTime);
     55             return true;
     56         } catch (Exception e) {
     57             e.printStackTrace();
     58             return false;
     59         }
     60     }
     61 
     62     /**
     63      * members(K key)获取变量中的值。
     64      *
     65      * @param key 键    
     66      * @return 返回Set对象    
     67      */
     68 
     69     @Override
     70     public Set<Object> members(String key) {
     71         return redisTemplate.opsForSet().members(key);
     72     }
     73 
     74     /**
     75      * 获取变量中值的长度。    
     76      *
     77      * @param key 键    
     78      * @return 返回SET的长度    
     79      */
     80     @Override
     81     public long size(String key) {
     82         return redisTemplate.opsForSet().size(key);
     83     }
     84 
     85     /**
     86      * 检查给定的元素是否在变量中。    
     87      *
     88      * @param key 键    
     89      * @param o   要检查的变量    
     90      * @return true存在 false不存在    
     91      */
     92     @Override
     93     public boolean isMember(String key, Object o) {
     94         return redisTemplate.opsForSet().isMember(key, o);
     95     }
     96 
     97     /**
     98      * 转移变量的元素值到目的变量。    
     99      *
    100      * @param key       键    
    101      * @param value     要转移的元素    
    102      * @param destValue 目标键    
    103      * @return true 成功 false 失败    
    104      */
    105     @Override
    106     public boolean move(String key, Object value, String destValue) {
    107         return redisTemplate.opsForSet().move(key, value, destValue);
    108     }
    109 
    110     /**
    111      * 弹出变量中的元素。    
    112      *
    113      * @param key 键    
    114      * @return 返回弹出的元素    
    115      */
    116     @Override
    117     public Object pop(String key) {
    118         return redisTemplate.opsForSet().pop(key);
    119     }
    120 
    121     /**
    122      * 批量移除变量中的元素。
    123      *
    124      * @param values 要移除的元素  
    125      * @param key    键 
    126      * @return 返回移除元素个数    
    127      */
    128     @Override
    129     public long remove(String key, Object... values) {
    130         return redisTemplate.opsForSet().remove(key, values);
    131     }
    132 
    133     /**
    134      * 匹配获取键值对    
    135      *
    136      * @param key     键    
    137      * @param options 选项    
    138      * @return 返回键值对    
    139      */
    140     @Override
    141     public Cursor<Object> scan(String key, ScanOptions options) {
    142         return redisTemplate.opsForSet().scan(key, options);
    143     }
    144 
    145     /**
    146      * 通过集合求差值。    
    147      *
    148      * @param key  键    
    149      * @param list LIST中的对象是要比较缓存的KEY    
    150      * @return 返回差差值    
    151      */
    152     @Override
    153     public Set<Object> difference(String key, List list) {
    154         return redisTemplate.opsForSet().difference(key, list);
    155     }
    156 
    157     @Override
    158     public Set<Object> difference(String key, String otherKeys) {
    159         return redisTemplate.opsForSet().difference(key, otherKeys);
    160     }
    161 
    162     /**
    163      * 将求出来的差值元素保存。    
    164      *
    165      * @param key      键    
    166      * @param otherKey 要比较的缓存键    
    167      * @param destKey  要保存差值的缓存键    
    168      */
    169     @Override
    170     public void differenceAndStore(String key, String otherKey, String destKey) {
    171         redisTemplate.opsForSet().differenceAndStore(key, otherKey, destKey);
    172     }
    173 
    174     /**
    175      * 将求出来的差值元素保存。    
    176      *
    177      * @param key       键    
    178      * @param otherKeys 要比较的多个缓存键    
    179      * @param destKey   要保存差值的缓存键    
    180      */
    181 
    182     @Override
    183     public void differenceAndStore(String key, List otherKeys, String destKey) {
    184         redisTemplate.opsForSet().differenceAndStore(key, otherKeys, destKey);
    185     }
    186 
    187     /**
    188      * 获取去重的随机元素。    
    189      *
    190      * @param key   键    
    191      * @param count 数量    
    192      * @return 返回随机元素    
    193      */
    194     @Override
    195     public Set<Object> distinctRandomMembers(String key, long count) {
    196         return redisTemplate.opsForSet().distinctRandomMembers(key, count);
    197     }
    198 
    199     /**
    200      * 获取2个变量中的交集。    
    201      *
    202      * @param key      键    
    203      * @param otherKey 比较的缓存键    
    204      * @return 返回交集    
    205      */
    206     @Override
    207     public Set<Object> intersect(String key, String otherKey) {
    208         return redisTemplate.opsForSet().intersect(key, otherKey);
    209     }
    210 
    211     @Override
    212     public Set<Object> intersect(String key, List list) {
    213         return redisTemplate.opsForSet().intersect(key, list);
    214     }
    215 
    216     /**
    217      *          
    218      * 获取2个变量交集后保存到最后一个参数上
    219      *
    220      * @param key      键
    221      * @param otherKey 其它的缓存键    
    222      * @param destKey  交集键  
    223      */
    224     @Override
    225     public void intersectAndStore(String key, String otherKey, String destKey) {
    226         redisTemplate.opsForSet().intersectAndStore(key, otherKey, destKey);
    227     }
    228 
    229     /**
    230      * 获取2个变量交集后保存到最后一个参数上             
    231      *
    232      * @param key      键
    233      * @param otherKey 其它的缓存键列表
    234      * @param destKey  交集键    
    235      */
    236     @Override
    237     public void intersectAndStore(String key, List otherKey, String destKey) {
    238         redisTemplate.opsForSet().intersectAndStore(key, otherKey, destKey);
    239     }
    240 
    241     /**
    242      * 获取2个变量的合集。                
    243      *
    244      * @param key      键  
    245      * @param otherKey 要合的键
    246      * @return 返回合并后的SET
    247      */
    248     @Override
    249     public Set<Object> union(String key, String otherKey) {
    250         return redisTemplate.opsForSet().union(key, otherKey);
    251     }
    252 
    253     @Override
    254     public Set<Object> union(String key, Set set) {
    255         return redisTemplate.opsForSet().union(key, set);
    256     }
    257 
    258     /**
    259      * 获取2个变量合集后保存到最后一个参数上。                
    260      *
    261      * @param key      键
    262      * @param otherKey 要合的键
    263      * @param destKey  合并后的键
    264      */
    265     @Override
    266     public void unionAndStore(String key, String otherKey, String destKey) {
    267         redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
    268     }
    269 
    270     /**
    271      * 获取2个变量合集后保存到最后一个参数上。    
    272      *
    273      * @param key     键    
    274      * @param list    要合的键列表    
    275      * @param destKey 合并后的键    
    276      */
    277     @Override
    278     public void unionAndStore(String key, List list, String destKey) {
    279         redisTemplate.opsForSet().unionAndStore(key, list, destKey);
    280     }
    281 
    282     /**
    283      * 随机获取变量中的元素。    
    284      *
    285      * @param key 键    
    286      * @return 返回其中一个随机元素    
    287      */
    288     @Override
    289     public Object randomMember(String key) {
    290         return redisTemplate.opsForSet().randomMember(key);
    291     }
    292 
    293     /**
    294      * 随机获取变量中指定个数的元素    
    295      *
    296      * @param key   键    
    297      * @param count 取随机数的个数
    298      */
    299 
    300     @Override
    301     public List<Object> randomMembers(String key, long count) {
    302         return redisTemplate.opsForSet().randomMembers(key, count);
    303     }
    304 
    305     @Override
    306     public void del(String... keys) {
    307         if (keys != null && keys.length > 0) {
    308             if (keys.length == 1) {
    309                 redisTemplate.delete(keys[0]);
    310             } else {
    311                 redisTemplate.delete(CollectionUtils.arrayToList(keys));
    312             }
    313         }
    314     }
    315     /**
    316      *    
    317      * 设置过期时间    
    318      *
    319      * @param key     键    
    320      * @param seconds 超时时间    
    321      * @return 成功 true 失败 false    
    322      **/
    323     @Override
    324     public boolean expire(String key, long seconds) {
    325         return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    326     }
    327 }
    SetCacheServiceImpl

     ZSet 类型代码示例

      1 package com.xq.serviceImpl.zset;
      2 
      3 import com.xq.service.ZSetCacheService;
      4 import com.xq.serviceImpl.list.ListCacheServiceImpl;
      5 import org.slf4j.Logger;
      6 import org.slf4j.LoggerFactory;
      7 import org.springframework.beans.factory.annotation.Autowired;
      8 import org.springframework.data.redis.connection.RedisZSetCommands;
      9 import org.springframework.data.redis.core.Cursor;
     10 import org.springframework.data.redis.core.RedisTemplate;
     11 import org.springframework.data.redis.core.ScanOptions;
     12 import org.springframework.data.redis.core.ZSetOperations;
     13 import org.springframework.stereotype.Service;
     14 import org.springframework.util.CollectionUtils;
     15 
     16 import java.util.List;
     17 import java.util.Set;
     18 
     19 @Service("zsetCacheService")
     20 public class ZSetCacheServiceImpl implements ZSetCacheService {
     21     private final static Logger log = LoggerFactory.getLogger(ZSetCacheServiceImpl.class);
     22     @Autowired
     23     private RedisTemplate<String, Object> redisTemplate;
     24 
     25     /**
     26      * 增添加元素到变量中同时指定元素的分值。    
     27      *
     28      * @param key   键    
     29      * @param value 值    
     30      * @param score 分值    
     31      * @return true 成功 false 失败    
     32      */
     33     public boolean add(String key, Object value, double score) {
     34         try {
     35             redisTemplate.opsForZSet().add(key, value, score);
     36             return true;
     37         } catch (Exception e) {
     38             e.printStackTrace();
     39             return false;
     40         }
     41     }
     42 
     43     /**
     44      * 获取变量指定区间的元素。START为0,END为-1代表取全部    
     45      *
     46      * @param key   键    
     47      * @param start 开始位置    
     48      * @param end   结束位置    
     49      * @return 返回SET    
     50      */
     51     @Override
     52     public Set<Object> range(String key, long start, long end) {
     53         return redisTemplate.opsForZSet().range(key, start, end);
     54     }
     55 
     56     /**
     57      * 用于获取满足非score的排序取值。这个排序只有在有相同分数的情况下才能使用,如果有不同的分数则返回值不 确定。    
     58      *
     59      * @param key   键    
     60      * @param range    
     61      * @return 返回SET    
     62      */
     63     public Set<Object> rangeByLex(String key, RedisZSetCommands.Range range) {
     64         return redisTemplate.opsForZSet().rangeByLex(key, range);
     65     }
     66 
     67     /**
     68      * 获取变量中元素的个数    
     69      *
     70      * @param key 键    
     71      * @return 返回个数    
     72      */
     73     public long zCard(String key) {
     74         return redisTemplate.opsForZSet().zCard(key);
     75     }
     76 
     77     /**
     78      * 获取区间值的个数。    
     79      *
     80      * @param key 键    
     81      * @param min 最小SCORE    
     82      * @param max 最大SCORE    
     83      * @return 返回数量    
     84      */
     85     @Override
     86     public long count(String key, double min, double max) {
     87         return redisTemplate.opsForZSet().count(key, min, max);
     88     }
     89 
     90     /**
     91      * 修改变量中的元素的分值。    
     92      *
     93      * @param key      
     94      * @param value    
     95      * @param delta    
     96      * @return    
     97      */
     98     @Override
     99     public double incrementScore(String key, Object value, double delta) {
    100         return redisTemplate.opsForZSet().incrementScore(key, value, delta);
    101     }
    102 
    103     /**
    104      * 获取元素的分值    
    105      *
    106      * @param key 键    
    107      * @param o   要查找的值    
    108      * @return 返回分值    
    109      */
    110     public double score(String key, Object o) {
    111         return redisTemplate.opsForZSet().score(key, o);
    112     }
    113 
    114     /**
    115      * 用于获取满足非score的设置下标开始的长度排序取值。    
    116      *
    117      * @param key   键    
    118      * @param range 范围    
    119      * @param limit 限制区域    
    120      * @return 返回SET    
    121      */
    122     @Override
    123     public Set<Object> rangeByLex(String key, RedisZSetCommands.Range range, RedisZSetCommands.Limit limit) {
    124         return redisTemplate.opsForZSet().rangeByLex(key, range, limit);
    125     }
    126 
    127     /**
    128      * 通过TypedTuple方式新增数据。    
    129      *
    130      * @param key    键    
    131      * @param tuples 元组    
    132      */
    133     @Override
    134     public void add(String key, Set<ZSetOperations.TypedTuple<Object>> tuples) {
    135         redisTemplate.opsForZSet().add(key, tuples);
    136     }
    137 
    138     /**
    139      * 根据设置的score获取区间值    
    140      *
    141      * @param key 键    
    142      * @param min 最小值    
    143      * @param max 最大值    
    144      * @return 返回SET    
    145      */
    146     @Override
    147     public Set<Object> rangeByScore(String key, double min, double max) {
    148         return redisTemplate.opsForZSet().rangeByScore(key, min, max);
    149     }
    150 
    151     /**
    152      * 根据设置的score获取区间值从给定下标和给定长度获取最终值。    
    153      *
    154      * @param key    键    
    155      * @param min    最小值    
    156      * @param max    最大值    
    157      * @param offset 偏移时    
    158      * @param count  取的长度    
    159      * @return 返回SET    
    160      */
    161     @Override
    162     public Set<Object> rangeByScore(String key, double min, double max, long offset, long count) {
    163         return redisTemplate.opsForZSet().rangeByScore(key, min, max, offset, count);
    164     }
    165 
    166     /**
    167      *    
    168      * 获取RedisZSetCommands.Tuples的区间值。    
    169      *
    170      * @param key   键    
    171      * @param start 开始SCORE值    
    172      * @param end     结束SCORE值    
    173      * @return 返回区间值    
    174      */
    175     @Override
    176     public Set<ZSetOperations.TypedTuple<Object>> rangeWithScores(String key, long start, long end) {
    177         return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
    178     }
    179 
    180     /**
    181      *    
    182      * 获取RedisZSetCommands.Tuples的区间值通过分值。    
    183      *
    184      * @param key 键    
    185      * @param min 最小分值    
    186      * @param max 最大分值    
    187      * @return 返回SET    
    188      */
    189     @Override
    190     public Set<ZSetOperations.TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max) {
    191         return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
    192     }
    193 
    194     /**
    195      *    
    196      * 获取RedisZSetCommands.Tuples的区间值从给定下标和给定长度获取最终值通过分值。    
    197      *
    198      * @param key    键    
    199      * @param min    最小分值    
    200      * @param max    最大分值    
    201      * @param offset 偏移量    
    202      * @param count  总数    
    203      * @return 返回SET    
    204      */
    205     @Override
    206     public Set<ZSetOperations.TypedTuple<Object>> rangeByScoreWithScores(String key, double min, double max, long offset, long count) {
    207         return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, offset, count);
    208     }
    209 
    210     /**
    211      *    
    212      * 获取变量中元素的索引,下标开始位置为    
    213      *
    214      * @param key 键    
    215      * @param o   要查找的值    
    216      * @return 返回下标    
    217      */
    218     @Override
    219     public long rank(String key, Object o) {
    220         return redisTemplate.opsForZSet().rank(key, o);
    221     }
    222 
    223     /**
    224      *    
    225      * 匹配获取键值对,ScanOptions.NONE为获取全部键值对; ScanOptions.scanOptions().match("C").build()匹配获取键位map1的键值对,不能模糊匹配。    
    226      *
    227      * @param key     键    
    228      * @param options 选项    
    229      * @return 返回键值对    
    230      */
    231     @Override
    232     public Cursor<ZSetOperations.TypedTuple<Object>> scan(String key, ScanOptions options) {
    233         return redisTemplate.opsForZSet().scan(key, options);
    234     }
    235 
    236     /**
    237      *    
    238      * 索引倒序排列指定区间元素。    
    239      *
    240      * @param key   键    
    241      * @param start 开始位置    
    242      * @param end   结束位置    
    243      * @return 返回倒排后的结果    
    244      */
    245     @Override
    246     public Set<Object> reverseRange(String key, long start, long end) {
    247         return redisTemplate.opsForZSet().reverseRange(key, start, end);
    248     }
    249 
    250     /**
    251      *    
    252      * 倒序排列指定分值区间元素。    
    253      *
    254      * @param key 键    
    255      * @param min 最小SCORE    
    256      * @param max 最大SCORE    
    257      * @return 返回区间元素    
    258      */
    259     @Override
    260     public Set<Object> reverseRangeByScore(String key, double min, double max) {
    261         return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
    262     }
    263 
    264     /**
    265      *    
    266      * 倒序排列从给定下标和给定长度分值区间元素。    
    267      *
    268      * @param key    键    
    269      * @param min    最小SCORE    
    270      * @param max    最大SCORE    
    271      * @param offset 偏移量    
    272      * @param count  数量    
    273      * @return 返回列表    
    274      */
    275     @Override
    276     public Set<Object> reverseRangeByScore(String key, double min, double max, long offset, long count) {
    277         return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, offset, count);
    278     }
    279 
    280     /**
    281      *    
    282      * 倒序排序获取RedisZSetCommands.Tuples的分值区间值。    
    283      *
    284      * @param key 键    
    285      * @param min 最小SCORE    
    286      * @param max 最大SCORE    
    287      * @return 返回SET集合    
    288      */
    289     @Override
    290     public Set<ZSetOperations.TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min, double max) {
    291         return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max);
    292     }
    293 
    294     /**
    295      *    
    296      * 序排序获取RedisZSetCommands.Tuples的从给定下标和给定长度分值区间值    
    297      *
    298      * @param key    键    
    299      * @param min    最小SCORE    
    300      * @param max    最大SCORE    
    301      * @param offset 偏移量    
    302      * @param count  总数    
    303      * @return 返回SET    
    304      */
    305     @Override
    306     public Set<ZSetOperations.TypedTuple<Object>> reverseRangeByScoreWithScores(String key, double min, double max, long offset, long count) {
    307         return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max, offset, count);
    308     }
    309 
    310     /**
    311      *    
    312      * 索引倒序排列区间值。    
    313      *
    314      * @param key   键    
    315      * @param start 开始Score    
    316      * @param end     结束SCORE    
    317      * @return      返回列表
    318      */
    319     @Override
    320     public Set<ZSetOperations.TypedTuple<Object>> reverseRangeWithScores(String key, long start, long end) {
    321         return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
    322     }
    323 
    324     /**
    325      *    
    326      * 获取倒序排列的索引值。    
    327      *
    328      * @param key 键    
    329      * @param o     值    
    330      * @return    返回倒序排列的索引值    
    331      */
    332     @Override
    333     public long reverseRank(String key, Object o) {
    334         return redisTemplate.opsForZSet().reverseRank(key, o);
    335     }
    336 
    337     /**
    338      *    
    339      * 获取2个变量的交集存放到第3个变量里面。    
    340      *
    341      * @param key      键    
    342      * @param otherKey 要交集的键    
    343      * @param destKey  目标键    
    344      * @return 返回交集长度    
    345      */
    346     @Override
    347     public long intersectAndStore(String key, String otherKey, String destKey) {
    348         return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey);
    349     }
    350 
    351     /**
    352      *    
    353      * 获取多个变量的交集存放到第3个变量里面。    
    354      *
    355      * @param key     键    
    356      * @param list    多个要交集的KEY    
    357      * @param destKey 要存入的KEY    
    358      * @return 返回数量    
    359      */
    360     @Override
    361     public long intersectAndStore(String key, List list, String destKey) {
    362         return redisTemplate.opsForZSet().intersectAndStore(key, list, destKey);
    363     }
    364 
    365     /**
    366      *    
    367      * 获取2个变量的合集存放到第3个变量里面。    
    368      *
    369      * @param key      键    
    370      * @param otherKey 要合并的KEY    
    371      * @param destKey  共同的并集元素存到destK    
    372      * @return 返回元素个数    
    373      */
    374     @Override
    375     public long unionAndStore(String key, String otherKey, String destKey) {
    376         return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
    377     }
    378 
    379     /**
    380      *    
    381      * 获取多个变量的合集存放到第3个变量里面。    
    382      *
    383      * @param key     键    
    384      * @param list    要合的集合KEY    
    385      * @param destKey 目票集合KEY    
    386      * @return 返回合集长度    
    387      */
    388     @Override
    389     public long unionAndStore(String key, List list, String destKey) {
    390         return redisTemplate.opsForZSet().unionAndStore(key, list, destKey);
    391     }
    392 
    393     /**
    394      *    
    395      * 批量移除元素根据元素值。    
    396      *
    397      * @param key    键    
    398      * @param values 要删除的元素    
    399      * @return 返回删除的数量    
    400      */
    401     @Override
    402     public long remove(String key, Object... values) {
    403         return redisTemplate.opsForZSet().remove(key, values);
    404     }
    405 
    406     /**
    407      * 根据分值移除区间元素。    
    408      *
    409      * @param key 键    
    410      * @param min 最小的SCORE    
    411      * @param max 最大的SCORE    
    412      * @return 返回移除的元素数量    
    413      */
    414     @Override
    415     public long removeRangeByScore(String key, double min, double max) {
    416         return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
    417     }
    418 
    419     /**
    420      * 根据索引值移除区间元素。    
    421      *
    422      * @param key   键    
    423      * @param start 索引开始    
    424      * @param end     索引结束
    425      * @return 返回移除的数量    
    426      */
    427     @Override
    428     public long removeRange(String key, long start, long end) {
    429         return redisTemplate.opsForZSet().removeRange(key, start, end);
    430     }
    431 
    432     /**
    433      * 删除指定的KEY的缓存    
    434      *
    435      * @param keys    
    436      */
    437     @Override
    438     public void del(String... keys) {
    439         if (keys != null && keys.length > 0) {
    440             if (keys.length == 1) {
    441                 redisTemplate.delete(keys[0]);
    442             } else {
    443                 redisTemplate.delete(CollectionUtils.arrayToList(keys));
    444             }
    445         }
    446     }
    447 }
    ZSetCacheServiceImpl
    博客园:https://www.cnblogs.com/xianquan
    Copyright ©2020 l-coil
    【转载文章务必保留出处和署名,谢谢!】
查看全文
  • 相关阅读:
    avalon做的抽奖效果
    [转]谈谈前端渲染 VS 后端渲染
    迷你MVVM框架 avalonjs 1.3.7发布
    迷你MVVM框架 avalonjs 学习教程22、avalon性能大揭密
    Facebook React 和 Web Components(Polymer)对比优势和劣势
    迷你MVVM框架 avalonjs 学习教程21、双向绑定链
    迷你MVVM框架 avalonjs 学习教程20、路由系统
    html中的数据岛:利用DSO和javascript在html中动态加载和浏览xml数据
    使用JS的 FileReader 读取本地文本文件(可兼容各种浏览器)
    简易版jquery
  • 原文地址:https://www.cnblogs.com/xianquan/p/13289494.html
  • Copyright © 2011-2022 走看看