Spring Cache指定CacheManager方式
更新時間:2025年05月12日 09:46:50 作者:joefany
這篇文章主要介紹了Spring Cache指定CacheManager方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Spring Cache指定CacheManager
配置文件application.properties中配置redis的相關(guān)配置
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方法里調(diào)用了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則會拋出異常,即必須指定一個
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
BufferedReader中read()方法和readLine()方法的使用
這篇文章主要介紹了BufferedReader中read()方法和readLine()方法的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
testNG項目通過idea Terminal命令行執(zhí)行的配置過程
這篇文章主要介紹了testNG項目通過idea Terminal命令行執(zhí)行,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-07-07
springboot2如何禁用自帶tomcat的session功能
這篇文章主要介紹了springboot2如何禁用自帶tomcat的session功能,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

