配置文件application.properties中配置redis的相关配置
spring.redis.database=
spring.redis.host=
spring.redis.port=
Spring Cache 配置文件
@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
private final RedisConnectionFactory redisConnectionFactory;
@Autowired
public CacheConfig(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
// 配置一个CacheManager 来支持spring cache的缓存注解
@Bean
public CacheManager cacheManager() {
RedisCacheConfiguration configuration = RedisCacheConfiguration
.defaultCacheConfig()
.entryTtl(Duration.ofDays(1)) //过期时间
;
return RedisCacheManager
.builder(redisConnectionFactory)
.cacheDefaults(configuration)
.build();
}
}
cacheManager()方法继承的是CachingConfigurerSupport类

AbstractCachingConfiguration是spring cache的配置文件加载方法,可以看到useCachingConfigurer方法里调用了cacheManager方法,就这样完成了指定spring cache的 CacheManager
@Configuration
public abstract class AbstractCachingConfiguration implements ImportAware {
......省略
@Autowired(required = false)
void setConfigurers(Collection<CachingConfigurer> configurers) {
if (CollectionUtils.isEmpty(configurers)) {
return;
}
if (configurers.size() > 1) {
throw new IllegalStateException(configurers.size() + " implementations of " +
"CachingConfigurer were found when only 1 was expected. " +
"Refactor the configuration such that CachingConfigurer is " +
"implemented only once or not at all.");
}
CachingConfigurer configurer = configurers.iterator().next();
useCachingConfigurer(configurer);
}
/**
* Extract the configuration from the nominated {@link CachingConfigurer}.
*/
protected void useCachingConfigurer(CachingConfigurer config) {
this.cacheManager = config::cacheManager;
this.cacheResolver = config::cacheResolver;
this.keyGenerator = config::keyGenerator;
this.errorHandler = config::errorHandler;
}
}
若不指定CacheManager,会从spring容器中查找是否有存在CacheManager,若存在一个CacheManager会使用该CacheManager,若存在多个CacheManager则会抛出异常,即必须指定一个。

本文详细介绍了如何在Spring Boot应用中配置Redis作为缓存存储,并实现Spring Cache的集成。通过自定义CacheManager,可以设置缓存的过期时间等参数,确保数据的有效性和一致性。
1780

被折叠的 条评论
为什么被折叠?



