zoukankan      html  css  js  c++  java
  • spring boot集成redis缓存

    上一个文字讲了redis的安装与运行,本次就不再赘述,本文讲解使用spring boot项目集成redis

    第一步:先看下项目目录构成,红框的部分是redis的类与配置内容,如下:

    1、增加redis依赖项,在pom文件中增加

      <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <version>2.1.0.RELEASE</version>
            </dependency>

    2、创建redis的配置类RedisConfig

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

    3、创建redis工具类RedisUtil

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

    4、配置文件中添加redis的配置项

    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=127.0.0.1
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    #连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=300

     以上内容配置内容就完成了。接下来通过Controller来验证redis相关配置

    1、控制器中增加如下代码:

     1 package com.yl.demo.controller;
     2 
     3 import com.yl.demo.bean.userinfo;
     4 import com.yl.demo.service.userinfoService;
     5 import com.yl.demo.utils.RedisUtil;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.RestController;
     9 
    10 import javax.annotation.Resource;
    11 import java.util.List;
    12 
    13 @RestController
    14 @RequestMapping("user")
    15 public class UsersController {
    16     @Autowired
    17     userinfoService userinfoService;
    18     private static int ExpireTime = 60;   // redis中存储的过期时间60s
    19     @Resource
    20     private RedisUtil redisUtil;
    21 
    22     @RequestMapping("demo")
    23     public String demo(){
    24         List<userinfo> list=userinfoService.selectAlluserinfo();
    25         list.stream().forEach(System.out::print);
    26         return  list.toString()+".";
    27     }
    28 
    29     @RequestMapping("set")
    30     public boolean redisset(String key, String value){
    31         //return redisUtil.set(key,userEntity,ExpireTime);
    32         return redisUtil.set(key,value);
    33     }
    34 
    35     @RequestMapping("get")
    36     public Object redisget(String key){
    37         return redisUtil.get(key);
    38     }
    39 
    40     @RequestMapping("expire")
    41     public boolean expire(String key){
    42         return redisUtil.expire(key,ExpireTime);
    43     }
    44 }

    2、通过浏览器访问http://localhost:8080/user/set?key=redis&value=redis

      此方法是写入redis内容,key为redis,值为redis值

    3、我们通过get方式获取下上一个方法写入到redis的值,看是否正常

           访问http://localhost:8080/user/get?key=redis,页面显示如下,表示成功

     至此,redis就集成到spring boot中了,可以尽情使用了。

  • 相关阅读:
    C# 16进制与字符串、字节数组之间的转换
    多文件上传方法
    超链接如何下载文件txt,word,excel等等
    asp.net不同类型文件读取处理
    .net二进制图片存储与读取的常见方法
    c#事务
    C#中的null和数据库中的null的区别
    Asp.net中Response.Charset 与Response.ContentEncoding区别
    导出到word
    js导出word
  • 原文地址:https://www.cnblogs.com/yangleikingly/p/13288146.html
Copyright © 2011-2022 走看看