SpringBoot整合Redis及Redis工具类撰写

一.导入依赖

  1. 所依赖的springboot版本
    1  <parent>
    2         <groupId>org.springframework.boot</groupId>
    3         <artifactId>spring-boot-starter-parent</artifactId>
    4         <version>2.1.14.RELEASE</version>
    5         <relativePath/> <!-- lookup parent from repository -->
    6     </parent>
  2. 加入redis以及需要序列化所用到的依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.5</version>
            </dependency>

     

二.application.properties和application.yml中配置redis

  1. application.properties中配置
     1 # Redis数据库索引(默认为0)  
     2 spring.redis.database=0  
     3 # Redis服务器地址  
     4 spring.redis.host=服务器ip
     5 # Redis服务器连接端口  
     6 spring.redis.port=6379  
     7 # Redis服务器连接密码(默认为空)  
     8 spring.redis.password=  
     9 # 连接池最大连接数(使用负值表示没有限制)  
    10 spring.redis.pool.max-active=200  
    11 # 连接池最大阻塞等待时间(使用负值表示没有限制)  
    12 spring.redis.pool.max-wait=-1  
    13 # 连接池中的最大空闲连接  
    14 spring.redis.pool.max-idle=10 
    15 # 连接池中的最小空闲连接  
    16 spring.redis.pool.min-idle=0  
    17 # 连接超时时间(毫秒)  
    18 spring.redis.timeout=1000 

     

  2. application.yml中配置
    1 spring:
    2   redis:
    3     port: 6379
    4     host: 123.57.0.0 # 服务器ip

     

三.redis配置类 

 

 1 package com.liuli.redission.config;
 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.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.RedisTemplate;
10 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
11 import org.springframework.data.redis.serializer.StringRedisSerializer;
12 
13 /**
14  * @Author: LiuLi
15  * @Description: redis配置类
16  * @Date: Create in 16:24 2020/9/2
17  */
18 @Configuration
19 public class RedisConfig {
20     @Bean
21     public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
22         RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
23         template.setConnectionFactory(factory);
24         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
25 
26         ObjectMapper om = new ObjectMapper();
27         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
28 
29         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
30         jackson2JsonRedisSerializer.setObjectMapper(om);
31 
32         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
33         // key采用String的序列化方式
34         template.setKeySerializer(stringRedisSerializer);
35         // hash的key也采用String的序列化方式
36         template.setValueSerializer(stringRedisSerializer);
37         // value序列化方式采用jackson
38         template.setValueSerializer(jackson2JsonRedisSerializer);
39         // hash的value序列化方式采用jackson
40         template.setHashValueSerializer(jackson2JsonRedisSerializer);
41         template.afterPropertiesSet();
42 
43         return template;
44     }
45 }

 

四、写一个Redis工具类

    

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

 

 

五、小结

  参考:   https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html 



 

posted @ 2020-09-02 18:23  liuli_warriors  阅读(504)  评论(0编辑  收藏  举报