赞
踩
1.导入cache依赖包
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
2.yml配置 选择Redis作为存储
- cache:
- type: redis
- redis: #单位毫秒
- time-to-live: 360000
- key-prefix: CACHE_ #key前缀
- use-key-prefix: true #是否开启key前缀
- cache-null-values: true #是否缓存空值
3.编写RedisCacheConfig配置文件
- package com.atguigu.gulimall.product.config;
-
- import org.springframework.boot.autoconfigure.cache.CacheProperties;
- import org.springframework.boot.context.properties.EnableConfigurationProperties;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.cache.RedisCacheConfiguration;
- import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.RedisSerializationContext;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
-
- /**
- * 我RedisCache配置
- *
- * @author 万天铭
- * @date 2022/05/14
- */
- @EnableConfigurationProperties(CacheProperties.class) //启用配置文件方式
- @Configuration
- @EnableCaching //开启RedisCache
- public class MyCacheConfig {
-
- /**
- * RedisCache配置
- *
- * @return {@link RedisCacheConfiguration}
- */
- @Bean
- RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
- //将配置key value 序列化
- RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
- config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
- config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
-
-
- //将配置文件中的所有配置都生效
- CacheProperties.Redis redisProperties = cacheProperties.getRedis();
- if (redisProperties.getTimeToLive() != null) {
- config = config.entryTtl(redisProperties.getTimeToLive());
- }
- if (redisProperties.getKeyPrefix() != null) {
- config = config.prefixKeysWith(redisProperties.getKeyPrefix());
- }
- if (!redisProperties.isCacheNullValues()) {
- config = config.disableCachingNullValues();
- }
- if (!redisProperties.isUseKeyPrefix()) {
- config = config.disableKeyPrefix();
- }
- return config;
- }
- }
(Cache在分布式下还是比较鸡肋的,个人推荐还是使用RedisTemplate比较好一点)
4.Spring Cache 注解作用
@Cachecble 触发将数据保存到缓存的操作
@CacheEvicet 触发将数据从缓存中删除
@CachePut 不影响方法执行更新缓存
@Caching 组和以上的多个操作
@CacheConfig 在类级别共享缓存的相同配置
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。