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接口,被序列化除屬性內容還有其他 內容,長度長且不易閱讀,默認就是采用這種序列化方式
存儲內容如下:
"\xac\xed\x00\x05sr\x00!com.oreilly.springdata.redis.User\xb1\x1c \n\xcd\xed%\xd8\x02\x00\x02I\x00\x03ageL\x00\buserNamet\x00\x12Ljava/lang/String;xp\x00\x00\x00\ x14t\x00\x05user1"
           <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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM