当前位置:   article > 正文

Spring Cache Redis配置_cachekeyprefix 前缀拼接

cachekeyprefix 前缀拼接

1.导入cache依赖包

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>

2.yml配置 选择Redis作为存储

  1. cache:
  2. type: redis
  3. redis: #单位毫秒
  4. time-to-live: 360000
  5. key-prefix: CACHE_ #key前缀
  6. use-key-prefix: true #是否开启key前缀
  7. cache-null-values: true #是否缓存空值

3.编写RedisCacheConfig配置文件

  1. package com.atguigu.gulimall.product.config;
  2. import org.springframework.boot.autoconfigure.cache.CacheProperties;
  3. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  8. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  9. import org.springframework.data.redis.serializer.RedisSerializationContext;
  10. import org.springframework.data.redis.serializer.StringRedisSerializer;
  11. /**
  12. * 我RedisCache配置
  13. *
  14. * @author 万天铭
  15. * @date 2022/05/14
  16. */
  17. @EnableConfigurationProperties(CacheProperties.class) //启用配置文件方式
  18. @Configuration
  19. @EnableCaching //开启RedisCache
  20. public class MyCacheConfig {
  21. /**
  22. * RedisCache配置
  23. *
  24. * @return {@link RedisCacheConfiguration}
  25. */
  26. @Bean
  27. RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
  28. //将配置key value 序列化
  29. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
  30. config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
  31. config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  32. //将配置文件中的所有配置都生效
  33. CacheProperties.Redis redisProperties = cacheProperties.getRedis();
  34. if (redisProperties.getTimeToLive() != null) {
  35. config = config.entryTtl(redisProperties.getTimeToLive());
  36. }
  37. if (redisProperties.getKeyPrefix() != null) {
  38. config = config.prefixKeysWith(redisProperties.getKeyPrefix());
  39. }
  40. if (!redisProperties.isCacheNullValues()) {
  41. config = config.disableCachingNullValues();
  42. }
  43. if (!redisProperties.isUseKeyPrefix()) {
  44. config = config.disableKeyPrefix();
  45. }
  46. return config;
  47. }
  48. }

(Cache在分布式下还是比较鸡肋的,个人推荐还是使用RedisTemplate比较好一点)

4.Spring Cache 注解作用

@Cachecble 触发将数据保存到缓存的操作

@CacheEvicet 触发将数据从缓存中删除 

@CachePut 不影响方法执行更新缓存

@Caching 组和以上的多个操作

@CacheConfig 在类级别共享缓存的相同配置

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/157148
推荐阅读
相关标签
  

闽ICP备14008679号