Redis封装和配置

1.RedisUtils.java

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

2.RedisConf.java

  1 import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2 import com.fasterxml.jackson.annotation.PropertyAccessor;
  3 import com.fasterxml.jackson.databind.ObjectMapper;
  4 import org.springframework.cache.annotation.CachingConfigurerSupport;
  5 import org.springframework.cache.annotation.EnableCaching;
  6 import org.springframework.context.annotation.Bean;
  7 import org.springframework.context.annotation.Configuration;
  8 import org.springframework.data.redis.connection.RedisConnectionFactory;
  9 import org.springframework.data.redis.core.*;
 10 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 11 import org.springframework.data.redis.serializer.StringRedisSerializer;
 12 
 13 /**
 14  * redis配置类
 15  */
 16 @Configuration
 17 //开启注解
 18 @EnableCaching
 19 public class RedisConfig extends CachingConfigurerSupport {
 20 
 21     /**
 22      * retemplate相关配置
 23      * @param factory
 24      * @return
 25      */
 26     @Bean
 27     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
 28 
 29         RedisTemplate<String, Object> template = new RedisTemplate<>();
 30         // 配置连接工厂
 31         template.setConnectionFactory(factory);
 32 
 33         //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
 34         Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
 35 
 36         ObjectMapper om = new ObjectMapper();
 37         // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
 38         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
 39         // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
 40         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
 41         jacksonSeial.setObjectMapper(om);
 42 
 43         // 值采用json序列化
 44         template.setValueSerializer(jacksonSeial);
 45         //使用StringRedisSerializer来序列化和反序列化redis的key值
 46         template.setKeySerializer(new StringRedisSerializer());
 47 
 48         // 设置hash key 和value序列化模式
 49         template.setHashKeySerializer(new StringRedisSerializer());
 50         template.setHashValueSerializer(jacksonSeial);
 51         template.afterPropertiesSet();
 52 
 53         return template;
 54     }
 55 
 56     /**
 57      * 对hash类型的数据操作
 58      *
 59      * @param redisTemplate
 60      * @return
 61      */
 62     @Bean
 63     public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
 64         return redisTemplate.opsForHash();
 65     }
 66 
 67     /**
 68      * 对redis字符串类型数据操作
 69      *
 70      * @param redisTemplate
 71      * @return
 72      */
 73     @Bean
 74     public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
 75         return redisTemplate.opsForValue();
 76     }
 77 
 78     /**
 79      * 对链表类型的数据操作
 80      *
 81      * @param redisTemplate
 82      * @return
 83      */
 84     @Bean
 85     public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
 86         return redisTemplate.opsForList();
 87     }
 88 
 89     /**
 90      * 对无序集合类型的数据操作
 91      *
 92      * @param redisTemplate
 93      * @return
 94      */
 95     @Bean
 96     public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
 97         return redisTemplate.opsForSet();
 98     }
 99 
100     /**
101      * 对有序集合类型的数据操作
102      *
103      * @param redisTemplate
104      * @return
105      */
106     @Bean
107     public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
108         return redisTemplate.opsForZSet();
109     }
110 }
原文地址:https://www.cnblogs.com/Fantastic-Code/p/11752495.html