Spring Cache 指定CacheManager

配置文件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类

Spring Cache 指定CacheManager_第1张图片

AbstractCachingConfiguration是spring cache的配置文件加载方法,可以看到useCachingConfigurer方法里调用了cacheManager方法,就这样完成了指定spring cache的 CacheManager
@Configuration
public abstract class AbstractCachingConfiguration implements ImportAware {
     ......省略

	@Autowired(required = false)
	void setConfigurers(Collection 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则会抛出异常,即必须指定一个。

你可能感兴趣的:(java,spring,spring,boot)