zoukankan      html  css  js  c++  java
  • spring boot 2.0+中整合redis 方法缓存Cache和普通缓存两种

    1、加入包

     1 <dependency>
     2             <groupId>org.springframework.boot</groupId>
     3             <artifactId>spring-boot-starter-cache</artifactId>
     4         </dependency>
     5         <dependency>
     6             <groupId>org.springframework.boot</groupId>
     7             <artifactId>spring-boot-starter-data-redis</artifactId>
     8             <exclusions>
     9                 <exclusion>
    10                     <groupId>redis.clients</groupId>
    11                     <artifactId>jedis</artifactId>
    12                 </exclusion>
    13                 <exclusion>
    14                     <groupId>io.lettuce</groupId>
    15                     <artifactId>lettuce-core</artifactId>
    16                 </exclusion>
    17             </exclusions>
    18         </dependency>
    19         <dependency>
    20             <groupId>redis.clients</groupId>
    21             <artifactId>jedis</artifactId>
    22         </dependency>
    maven

    2、配置文件使用哪一个库

    spring.redis.database=0
    application.properties

    3、新建配置文件redis.properties

    redis.host=xxxxx
    redis.port=xxx
    redis.pass=
    redis.timeout=3600
    redis.jedis.pool.max-idle=8
    redis.jedis.pool.max-wait=-1
    redis.properties

    4、增加配置类 JedisRedisConfig

     1 @Configuration
     2 @PropertySource("classpath:/config/redis.properties")
     3 public class JedisRedisConfig {
     4     @Value("${redis.host}")
     5     private  String host;
     6     @Value("${redis.pass}")
     7     private  String password;
     8     @Value("${redis.port}")
     9     private  int port;
    10     @Value("${redis.timeout}")
    11     private  int timeout;
    12     @Value("${redis.jedis.pool.max-idle}")
    13     private int maxIdle;
    14     @Value("${redis.jedis.pool.max-wait}")
    15     private long maxWaitMillis;
    16 
    17     @Bean
    18     public JedisConnectionFactory jedisConnectionFactory() {
    19         RedisStandaloneConfiguration configuration =
    20                 new RedisStandaloneConfiguration(host, port);
    21         return new JedisConnectionFactory(configuration);
    22     }
    23     @Bean
    24     public JedisPool redisPoolFactory() {
    25         JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    26         jedisPoolConfig.setMaxIdle(maxIdle);
    27         jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
    28 
    29         JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
    30         return jedisPool;
    31     }
    32 }
    配置类

    5、增加redis缓存配置类

     1 @Configuration
     2 @EnableCaching
     3 public class RedisConfig extends CachingConfigurerSupport {
     4 
     5     @Autowired
     6     private JedisConnectionFactory jedisConnectionFactory;
     7 
     8     /**
     9      * @description 自定义的缓存key的生成策略
    10      *              若想使用这个key  只需要讲注解上keyGenerator的值设置为keyGenerator即可</br>
    11      * @return 自定义策略生成的key
    12      */
    13     @Bean
    14     public KeyGenerator keyGenerator() {
    15         return new KeyGenerator(){
    16             @Override
    17             public Object generate(Object target, Method method, Object... params) {
    18                 StringBuffer sb = new StringBuffer();
    19                 sb.append(target.getClass().getName());
    20                 sb.append(method.getName());
    21                 for(Object obj:params){
    22                     sb.append(obj.toString());
    23                 }
    24                 return sb.toString();
    25             }
    26         };
    27     }
    28 
    29     //缓存管理器
    30     @Bean
    31     public CacheManager cacheManager(JedisConnectionFactory jedisConnectionFactory) {
    32         RedisCacheConfiguration redisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig()
    33                 .entryTtl(Duration.ofMinutes(30));
    34         return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(jedisConnectionFactory))
    35                 .cacheDefaults(redisCacheConfiguration).build();
    36     }
    37 
    38     /**
    39      * RedisTemplate配置
    40      *
    41      * @param jedisConnectionFactory
    42      * @return
    43      */
    44     @Bean
    45     public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
    46         //设置序列化
    47         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    48         ObjectMapper om = new ObjectMapper();
    49         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    50         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    51         jackson2JsonRedisSerializer.setObjectMapper(om);
    52         //配置redisTemplate
    53         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    54         redisTemplate.setConnectionFactory(jedisConnectionFactory);
    55         RedisSerializer stringSerializer = new StringRedisSerializer();
    56         redisTemplate.setKeySerializer(stringSerializer);//key序列化
    57         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);//value序列化
    58         redisTemplate.setHashKeySerializer(stringSerializer);//Hash key序列化
    59         redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);//Hash value序列化
    60         redisTemplate.afterPropertiesSet();
    61         return redisTemplate;
    62     }
    63 //    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    64 //        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    65 //        redisTemplate.setConnectionFactory(redisConnectionFactory);
    66 //        // 替换默认序列化 方式
    67 //        GenericFastJson2JsonRedisSerializer genericFastJson2JsonRedisSerializer = new GenericFastJson2JsonRedisSerializer();
    68 //        redisTemplate.setValueSerializer(genericFastJson2JsonRedisSerializer);
    69 //        redisTemplate.setKeySerializer(genericFastJson2JsonRedisSerializer);
    70 //        redisTemplate.afterPropertiesSet();
    71 //        return redisTemplate;
    72 //    }
    73 }
    redis缓存配置类

    6、redis工具类

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

    7、使用示例

    1 redisUtil.set("1024","设置时间配置",1, TimeUnit.DAYS);
    2 redisUtil.get("1024");
    普通设置和获取
    1 @Cacheable(cacheNames = "test",key = "#key")
    2     public String test(String key) {
    3         return UUID.randomUUID().toString();
    4     }
    方法的缓存
  • 相关阅读:
    使用牛顿迭代法和二分法求解一个数的平方根(python语言实现)
    厄拉多塞筛法和普通方法求素数表(python实现)
    使用辗转相除法求两个数的最大公因数(python实现)
    我在博客园第一篇博文
    Linux安装maven
    MyBatis基础入门
    Maven的使用入门
    nginx的简单使用和使用nginx在windows上搭建tomcat集群
    后端程序员如何玩转AJAX
    Servlet3.0文件上传
  • 原文地址:https://www.cnblogs.com/rolayblog/p/11262690.html
Copyright © 2011-2022 走看看