当前位置:   article > 正文

spring-boot集成redis实现缓存功能

spring.cache.redis.use-key-prefix

一、本次案例

我们假设用户信息(user)和产品信息(product)需要缓存,缓存数据都加上user和product作为key前缀,采用用户的id和产品的id作为key的后缀。用户缓存时间为30分钟,产品信息缓存时间为10分钟。

二、redis客户端配置

无论使用spring-boot的哪个版本,我们都需要先配置redis连接,两个版本的redis客户端连接池使用有所不同。

spring-boot版本默认客户端类型
1.5.xjedis
2.xlettuce

在1.5.x中,我们配置jedis连接池只需要配置 spring.redis.pool.* 开始的配置即可,如下配置

  1. spring.redis.pool.max-active=8
  2. spring.redis.pool.max-wait=-1
  3. spring.redis.pool.min-idle=0
  4. spring.redis.pool.max-idle=8

但在2.x版本中由于引入了不同的客户端,需要指定配置哪种连接池,如下配置

  1. #jedis客户端
  2. spring.redis.jedis.pool.max-active=8
  3. spring.redis.jedis.pool.max-wait=-1ms
  4. spring.redis.jedis.pool.min-idle=0
  5. spring.redis.jedis.pool.max-idle=8
  6. #lettuce客户端
  7. spring.redis.lettuce.pool.min-idle=0
  8. spring.redis.lettuce.pool.max-idle=8
  9. spring.redis.lettuce.pool.max-wait=-1ms
  10. spring.redis.lettuce.pool.max-active=8
  11. spring.redis.lettuce.shutdown-timeout=100ms

除此之外还可以看到时间配置上还需要带上对应的单位。

三、直接配置cache参数

在1.5.x版本下提供的针对cache的配置非常少,我们能够使用到的自动装配redis缓存的配置如下

  1. #缓存的名称集合,多个采用逗号分割
  2. spring.cache.cache-names=
  3. #缓存的类型,官方提供了很多,这里我们填写redis
  4. spring.cache.type=

在2.x版本时,官方增加了更多的配置

  1. #缓存的名称集合,多个采用逗号分割
  2. spring.cache.cache-names=
  3. #缓存的类型,官方提供了很多,这里我们填写redis
  4. spring.cache.type=
  5. #是否缓存null数据,默认是false
  6. spring.cache.redis.cache-null-values=
  7. #redis中缓存超时的时间,默认60000ms
  8. spring.cache.redis.time-to-live=
  9. #缓存数据key是否使用前缀,默认是true
  10. spring.cache.redis.use-key-prefix=
  11. #缓存数据key的前缀,在上面的配置为true时有效,
  12. spring.cache.redis.key-prefix=

四、JavaConfig方式配置

通用配置方式只能满足整个程序所有缓存都采用相同公共配置的方式,如果需要特殊处理,如我们的案列,则需要自己采用代码的方式来配置。
采用代码的方式,只要需要配置的是CacheMananger,采用Redis时具体实现我们需要使用其子类RedisCacheMananger来做配置

4.1、spring-boot 1.5.x版本

CacheManager配置
  1. @Bean
  2. public CacheManager cacheManager(RedisTemplate redisTemplate) {
  3. RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
  4. //默认超时时间,单位秒
  5. redisCacheManager.setDefaultExpiration(60);
  6. //缓存超时时间Map,key为cacheName,value为超时,单位是秒
  7. Map<String, Long> expiresMap = new HashMap<>();
  8. //缓存用户信息的cacheName和超时时间
  9. expiresMap.put("user", 1800L);
  10. //缓存产品信息的cacheName和超时时间
  11. expiresMap.put("product", 600L);
  12. redisCacheManager.setExpires(expiresMap);
  13. return redisCacheManager;
  14. }
cache调用代码
  1. @Cacheable(value = "user", key = "'user:'+#id", unless = "#result==null")
  2. public String getUser(int id) {
  3. //逻辑操作
  4. }
  5. @Cacheable(value = "product", key = "'product:'+#id", unless = "#result==null")
  6. public String getProduct(int id) {
  7. //逻辑操作
  8. }

4.2、spring-boot 2.x版本

CacheManager配置

2.x版本开始,代码方式配置变化比较大,同时增加了更多配置参数

  1. @Bean
  2. CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
  3. //user信息缓存配置
  4. RedisCacheConfiguration userCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)).disableCachingNullValues().prefixKeysWith("user");
  5. //product信息缓存配置
  6. RedisCacheConfiguration productCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)).disableCachingNullValues().prefixKeysWith("product");
  7. Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
  8. redisCacheConfigurationMap.put("user", userCacheConfiguration);
  9. redisCacheConfigurationMap.put("product", productCacheConfiguration);
  10. //初始化一个RedisCacheWriter
  11. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
  12. //设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现
  13. //ClassLoader loader = this.getClass().getClassLoader();
  14. //JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
  15. //RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jdkSerializer);
  16. //RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
  17. RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
  18. //设置默认超过期时间是30
  19. defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
  20. //初始化RedisCacheManager
  21. RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig, redisCacheConfigurationMap);
  22. return cacheManager;
  23. }

以上代码中RedisCacheConfiguration类为2.x新增的配置类,增加了几个配置项。这里比较奇怪的是调用它的配置方法每一次都会重新生成一个配置对象,而不是在原对象上直接修改参数值,这一点本人没搞懂作者为何要选择这种方式。

cache调用代码
  1. @Cacheable(value = "user", key = "#id", unless = "#result==null")
  2. public String getUser(int id) {
  3. //逻辑操作
  4. }
  5. @Cacheable(value = "product", key = "#id", unless = "#result==null")
  6. public String getProduct(int id) {
  7. //逻辑操作
  8. }

这里两点需要注意的地方

  • 1、在Cacheable的key属性中不在需要自己配置前缀,可以在RedisCacheConfiguration中配置。
  • 2、如果Cacheable中不配置 unless = "#result==null" 属性,而RedisCacheConfiguration中调用disableCachingNullValues()配置了不缓存null结果在出现null结果时会报异常,这一点与我一开始的理解也不太一样,二者并非都生效的。个人理解unless配置#result==null可以决定null的值是否往cacheManager丢,而RedisCacheConfiguration的disableCachingNullValues()只在存储前起到了校验作用,而不会因为设置了这个值而直接跳过null的保存。如果真是设计如此,感觉有点鸡肋,不知道算不算一个bug。

小结

spring-boot刚刚发布了2.0.0的正式版,除了比较大的webflux之外,许多组件可能都有细节变化,在做升级的时候需要注意更改,建议先验证常用的功能用法后,再做升级的计划安排。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号