RedisUtil写法,好用

代码:

  1 import org.springframework.beans.factory.annotation.Autowired;
  2 import org.springframework.data.redis.core.RedisTemplate;
  3 import org.springframework.stereotype.Component;
  4 import org.springframework.util.CollectionUtils;
  5 
  6 import java.util.List;
  7 import java.util.Map;
  8 import java.util.Set;
  9 import java.util.concurrent.TimeUnit;
 10 
 11 @Component
 12 public final class RedisUtil {
 13     @Autowired
 14     private RedisTemplate<String, Object> redisTemplate;
 15 
 16     // =============================common============================
 17 
 18     /**
 19      * 指定缓存失效时间
 20      *
 21      * @param key  键
 22      * @param time 时间(秒)
 23      */
 24 
 25     public boolean expire(String key, long time) {
 26         try {
 27             if (time > 0) {
 28                 redisTemplate.expire(key, time, TimeUnit.SECONDS);
 29             }
 30             return true;
 31         } catch (Exception e) {
 32             e.printStackTrace();
 33             return false;
 34         }
 35     }
 36 
 37     /**
 38      * 根据key 获取过期时间
 39      *
 40      * @param key 键 不能为null
 41      * @return 时间(秒) 返回0代表为永久有效
 42      */
 43 
 44     public long getExpire(String key) {
 45         return redisTemplate.getExpire(key, TimeUnit.SECONDS);
 46     }
 47 
 48     /**
 49      * 判断key是否存在
 50      *
 51      * @param key 键
 52      * @return true 存在 false不存在
 53      */
 54 
 55     public boolean hasKey(String key) {
 56         try {
 57             return redisTemplate.hasKey(key);
 58         } catch (Exception e) {
 59             e.printStackTrace();
 60             return false;
 61         }
 62     }
 63 
 64     /**
 65      * 删除缓存
 66      *
 67      * @param key 可以传一个值 或多个
 68      */
 69 
 70     @SuppressWarnings("unchecked")
 71     public void del(String... key) {
 72         if (key != null && key.length > 0) {
 73             if (key.length == 1) {
 74                 redisTemplate.delete(key[0]);
 75             } else {
 76                 redisTemplate.delete(CollectionUtils.arrayToList(key));
 77             }
 78         }
 79     }
 80 
 81 
 82     // ============================String=============================
 83 
 84     /**
 85      * 普通缓存获取
 86      *
 87      * @param key 键
 88      * @return 89      */
 90     public Object get(String key) {
 91         return key == null ? null : redisTemplate.opsForValue().get(key);
 92     }
 93 
 94     /**
 95      * 普通缓存放入
 96      *
 97      * @param key   键
 98      * @param value 值
 99      * @return true成功 false失败
100      */
101     public boolean set(String key, Object value) {
102         try {
103             redisTemplate.opsForValue().set(key, value);
104             return true;
105         } catch (Exception e) {
106             e.printStackTrace();
107             return false;
108         }
109     }
110 
111     /**
112      * 普通缓存放入并设置时间
113      *
114      * @param key   键
115      * @param value 值
116      * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
117      * @return true成功 false 失败
118      */
119     public boolean set(String key, Object value, long time) {
120         try {
121             if (time > 0) {
122                 redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
123             } else {
124                 set(key, value);
125             }
126             return true;
127         } catch (Exception e) {
128             e.printStackTrace();
129             return false;
130         }
131     }
132 
133     /**
134      * 递增
135      *
136      * @param key   键
137      * @param delta 要增加几(大于0)
138      */
139 
140     public long incr(String key, long delta) {
141         if (delta < 0) {
142             throw new RuntimeException("递增因子必须大于0");
143         }
144         return redisTemplate.opsForValue().increment(key, delta);
145     }
146 
147     /**
148      * 递减
149      *
150      * @param key   键
151      * @param delta 要减少几(小于0)
152      */
153 
154     public long decr(String key, long delta) {
155         if (delta < 0) {
156             throw new RuntimeException("递减因子必须大于0");
157         }
158         return redisTemplate.opsForValue().increment(key, -delta);
159     }
160 
161     // ================================Map=================================
162 
163     /**
164      * HashGet
165      *
166      * @param key  键 不能为null
167      * @param item 项 不能为null
168      * @return169      */
170 
171     public Object hget(String key, String item) {
172         return redisTemplate.opsForHash().get(key, item);
173     }
174 
175     /**
176      * 获取hashKey对应的所有键值
177      *
178      * @param key 键
179      * @return 对应的多个键值
180      */
181 
182     public Map<Object, Object> hmget(String key) {
183         return redisTemplate.opsForHash().entries(key);
184     }
185 
186     /**
187      * HashSet
188      *
189      * @param key 键
190      * @param map 对应多个键值
191      * @return true 成功 false 失败
192      */
193 
194     public boolean hmset(String key, Map<String, Object> map) {
195         try {
196             redisTemplate.opsForHash().putAll(key, map);
197             return true;
198         } catch (Exception e) {
199             e.printStackTrace();
200             return false;
201         }
202     }
203 
204     /**
205      * HashSet 并设置时间
206      *
207      * @param key  键
208      * @param map  对应多个键值
209      * @param time 时间(秒)
210      * @return true成功 false失败
211      */
212 
213     public boolean hmset(String key, Map<String, Object> map, long time) {
214         try {
215             redisTemplate.opsForHash().putAll(key, map);
216             if (time > 0) {
217                 expire(key, time);
218             }
219             return true;
220         } catch (Exception e) {
221             e.printStackTrace();
222             return false;
223         }
224 
225     }
226 
227     /**
228      * 向一张hash表中放入数据,如果不存在将创建
229      *
230      * @param key   键
231      * @param item  项
232      * @param value 值
233      * @return true 成功 false失败
234      */
235 
236     public boolean hset(String key, String item, Object value) {
237         try {
238             redisTemplate.opsForHash().put(key, item, value);
239             return true;
240         } catch (Exception e) {
241             e.printStackTrace();
242             return false;
243         }
244     }
245 
246     /**
247      * 向一张hash表中放入数据,如果不存在将创建
248      *
249      * @param key   键
250      * @param item  项
251      * @param value 值
252      * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
253      * @return true 成功 false失败
254      */
255 
256     public boolean hset(String key, String item, Object value, long time) {
257         try {
258             redisTemplate.opsForHash().put(key, item, value);
259             if (time > 0) {
260                 expire(key, time);
261             }
262             return true;
263         } catch (Exception e) {
264             e.printStackTrace();
265             return false;
266         }
267     }
268 
269     /**
270      * 删除hash表中的值
271      *
272      * @param key  键 不能为null
273      * @param item 项 可以使多个 不能为null
274      */
275 
276     public void hdel(String key, Object... item) {
277         redisTemplate.opsForHash().delete(key, item);
278     }
279 
280     /**
281      * 判断hash表中是否有该项的值
282      *
283      * @param key  键 不能为null
284      * @param item 项 不能为null
285      * @return true 存在 false不存在
286      */
287 
288     public boolean hHasKey(String key, String item) {
289         return redisTemplate.opsForHash().hasKey(key, item);
290     }
291 
292     /**
293      * hash递增 如果不存在,就会创建一个 并把新增后的值返回
294      *
295      * @param key  键
296      * @param item 项
297      * @param by   要增加几(大于0)
298      */
299 
300     public double hincr(String key, String item, double by) {
301         return redisTemplate.opsForHash().increment(key, item, by);
302     }
303 
304     /**
305      * hash递减
306      *
307      * @param key  键
308      * @param item 项
309      * @param by   要减少记(小于0)
310      */
311 
312     public double hdecr(String key, String item, double by) {
313         return redisTemplate.opsForHash().increment(key, item, -by);
314     }
315 
316     // ============================set=============================
317 
318     /**
319      * 根据key获取Set中的所有值
320      *
321      * @param key 键
322      */
323 
324     public Set<Object> sGet(String key) {
325         try {
326             return redisTemplate.opsForSet().members(key);
327         } catch (Exception e) {
328             e.printStackTrace();
329             return null;
330         }
331     }
332 
333     /**
334      * 根据value从一个set中查询,是否存在
335      *
336      * @param key   键
337      * @param value 值
338      * @return true 存在 false不存在
339      */
340 
341     public boolean sHasKey(String key, Object value) {
342         try {
343             return redisTemplate.opsForSet().isMember(key, value);
344         } catch (Exception e) {
345             e.printStackTrace();
346             return false;
347         }
348     }
349 
350     /**
351      * 将数据放入set缓存
352      *
353      * @param key    键
354      * @param values 值 可以是多个
355      * @return 成功个数
356      */
357 
358     public long sSet(String key, Object... values) {
359         try {
360             return redisTemplate.opsForSet().add(key, values);
361         } catch (Exception e) {
362             e.printStackTrace();
363             return 0;
364         }
365     }
366 
367     /**
368      * 将set数据放入缓存
369      *
370      * @param key    键
371      * @param time   时间(秒)
372      * @param values 值 可以是多个
373      * @return 成功个数
374      */
375 
376     public long sSetAndTime(String key, long time, Object... values) {
377         try {
378             Long count = redisTemplate.opsForSet().add(key, values);
379             if (time > 0)
380                 expire(key, time);
381             return count;
382         } catch (Exception e) {
383             e.printStackTrace();
384             return 0;
385         }
386     }
387 
388     /**
389      * 获取set缓存的长度
390      *
391      * @param key 键
392      */
393 
394     public long sGetSetSize(String key) {
395         try {
396             return redisTemplate.opsForSet().size(key);
397         } catch (Exception e) {
398             e.printStackTrace();
399             return 0;
400         }
401     }
402 
403     /**
404      * 移除值为value的
405      *
406      * @param key    键
407      * @param values 值 可以是多个
408      * @return 移除的个数
409      */
410 
411     public long setRemove(String key, Object... values) {
412         try {
413             Long count = redisTemplate.opsForSet().remove(key, values);
414             return count;
415         } catch (Exception e) {
416             e.printStackTrace();
417             return 0;
418         }
419     }
420 
421     // ===============================list=================================
422 
423     /**
424      * 获取list缓存的内容
425      *
426      * @param key   键
427      * @param start 开始
428      * @param end   结束 0 到 -1代表所有值
429      */
430 
431     public List<Object> lGet(String key, long start, long end) {
432         try {
433             return redisTemplate.opsForList().range(key, start, end);
434         } catch (Exception e) {
435             e.printStackTrace();
436             return null;
437         }
438     }
439 
440     /**
441      * 获取list缓存的长度
442      *
443      * @param key 键
444      */
445 
446     public long lGetListSize(String key) {
447         try {
448             return redisTemplate.opsForList().size(key);
449         } catch (Exception e) {
450             e.printStackTrace();
451             return 0;
452         }
453     }
454 
455     /**
456      * 通过索引 获取list中的值
457      *
458      * @param key   键
459      * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
460      */
461 
462     public Object lGetIndex(String key, long index) {
463         try {
464             return redisTemplate.opsForList().index(key, index);
465         } catch (Exception e) {
466             e.printStackTrace();
467             return null;
468         }
469     }
470 
471     /**
472      * 将list放入缓存
473      *
474      * @param key   键
475      * @param value 值
476      * @return
477      */
478 
479     public boolean lSet(String key, Object value) {
480         try {
481             redisTemplate.opsForList().rightPush(key, value);
482             return true;
483         } catch (Exception e) {
484             e.printStackTrace();
485             return false;
486         }
487     }
488 
489     /**
490      * 将list放入缓存
491      *
492      * @param key   键
493      * @param value 值
494      * @param time  时间(秒)
495      * @return
496      */
497 
498     public boolean lSet(String key, Object value, long time) {
499         try {
500             redisTemplate.opsForList().rightPush(key, value);
501             if (time > 0)
502                 expire(key, time);
503             return true;
504         } catch (Exception e) {
505             e.printStackTrace();
506             return false;
507         }
508     }
509 
510     /**
511      * 将list放入缓存
512      *
513      * @param key   键
514      * @param value 值
515      */
516 
517     public boolean lSet(String key, List<Object> value) {
518         try {
519             redisTemplate.opsForList().rightPushAll(key, value);
520             return true;
521         } catch (Exception e) {
522             e.printStackTrace();
523             return false;
524         }
525     }
526 
527     /**
528      * 将list放入缓存
529      *
530      * @param key   键
531      * @param value 值
532      * @param time  时间(秒)
533      */
534 
535     public boolean lSet(String key, List<Object> value, long time) {
536         try {
537             redisTemplate.opsForList().rightPushAll(key, value);
538             if (time > 0)
539                 expire(key, time);
540             return true;
541         } catch (Exception e) {
542             e.printStackTrace();
543             return false;
544         }
545     }
546 
547     /**
548      * 根据索引修改list中的某条数据
549      *
550      * @param key   键
551      * @param index 索引
552      * @param value 值
553      */
554 
555     public boolean lUpdateIndex(String key, long index, Object value) {
556         try {
557             redisTemplate.opsForList().set(key, index, value);
558             return true;
559         } catch (Exception e) {
560             e.printStackTrace();
561             return false;
562         }
563     }
564 
565     /**
566      * 移除N个值为value
567      *
568      * @param key   键
569      * @param count 移除多少个
570      * @param value 值
571      * @return 移除的个数
572      */
573 
574     public long lRemove(String key, long count, Object value) {
575         try {
576             Long remove = redisTemplate.opsForList().remove(key, count, value);
577             return remove;
578         } catch (Exception e) {
579             e.printStackTrace();
580             return 0;
581         }
582     }
583 }

配置文件写法:

 1 #springboot整合redis相关配置
 2 spring:
 3   # 环境 dev|test|prod
 4   profiles:
 5     active: dev
 6   servlet:
 7     multipart:
 8       max-file-size: 100MB
 9       max-request-size: 100MB
10       enabled: true
11   redis:
12     database: 0           # Redis服务器数据库
13     host: 192.168.1.202    # Redis服务器地址
14     port: 6379            # Redis服务器连接端口
15     password:      # Redis服务器连接密码(默认为空)
16     timeout: 6000ms       # 连接超时时间(毫秒)
17     jedis:
18       pool:
19         max-active: 200   # 连接池最大连接数(使用负值表示没有限制)
20         max-wait: -1      # 连接池最大阻塞等待时间(使用负值表示没有限制)
21         max-idle: 10      # 连接池中的最大空闲连接
22         min-idle: 0       # 连接池中的最小空闲连接
RedisConfig 配置代码:
 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 import org.springframework.data.redis.connection.RedisConnectionFactory;
 4 import org.springframework.data.redis.core.RedisTemplate;
 5 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 6 import org.springframework.data.redis.serializer.StringRedisSerializer;
 7 import com.fasterxml.jackson.annotation.JsonAutoDetect;
 8 import com.fasterxml.jackson.annotation.PropertyAccessor;
 9 import com.fasterxml.jackson.databind.ObjectMapper;
10 
11 @Configuration
12 public class RedisConfig {
13 
14     @Bean
15     @SuppressWarnings("all")
16     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
17 
18         RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
19 
20         template.setConnectionFactory(factory);
21 
22         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
23 
24         ObjectMapper om = new ObjectMapper();
25 
26         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
27 
28         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
29 
30         jackson2JsonRedisSerializer.setObjectMapper(om);
31 
32         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
33 
34         // key采用String的序列化方式
35 
36         template.setKeySerializer(stringRedisSerializer);
37 
38         // hash的key也采用String的序列化方式
39 
40         template.setHashKeySerializer(stringRedisSerializer);
41 
42         // value序列化方式采用jackson
43 
44         template.setValueSerializer(jackson2JsonRedisSerializer);
45 
46         // hash的value序列化方式采用jackson
47         template.setHashValueSerializer(jackson2JsonRedisSerializer);
48 
49         template.afterPropertiesSet();
50 
51         return template;
52 
53     }
54 
55 }
原文地址:https://www.cnblogs.com/wangquanyi/p/11329001.html