1.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.配置文件
spring:
redis:
host: 127.0.0.1
port: 6379
database: 3
password: 123456
cache:
type: REDIS
redis:
time-to-live: 360000000
3.缓存配置类(让配置文件中的配置生效,并设置key和value的序列化方式)
@EnableConfigurationProperties(CacheProperties.class) //开启配置文件支持,将CacheProperties 注册进ioc容器,相当于@Component注解
@Configuration
@EnableCaching
public class MyCacheConfig {
// @Autowired
// CacheProperties cacheProperties;
/**
*
* @return
*/
@Bean
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//key和value的序列化器
config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//让配置文件中的配置生效 ttl等
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;
}
}
4.实现列表缓存
主要看下缓存的key如何设计,我本次采用 方法名称+前端传递过的查询参数 组合作为缓存的key,
比如:key=getMyCategory:categoryid:name, 当然参数可能有多个,在后面拼接即可。
@Cacheable(value = {"categorys"}, key = "#root.methodName+':'+#request.categoryid+':'+#request.categoryiName")
@Override
public List<String> getMyCategory(CategoryRequest request) {
//查询的列表数据
}
5.缓存数据一致性问题
保证数据库数据和redis缓存的数据一致性,常用的有双写模式,失效模式,我本次采用失效模式,采用SpringCache的@CacheEvict注解,保证数据库数据更新之后,将redis中的缓存清除,下次查询,将最新的数据放入缓存。
正当少年时,以梦为马,不负韶华!