io.github.dengchen2020.cache.redis.RedisCacheAutoConfiguration Maven / Gradle / Ivy
package io.github.dengchen2020.cache.redis;
import io.github.dengchen2020.cache.CacheHelper;
import io.github.dengchen2020.cache.DefaultCacheHelper;
import io.github.dengchen2020.cache.properties.CacheSpecBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import java.util.HashMap;
import java.util.Map;
/**
* Redis缓存自动配置
*
* @author dengchen
* @since 2024/5/30
*/
@ConditionalOnClass(RedisConnectionFactory.class)
@EnableConfigurationProperties(CacheSpecBuilder.class)
@ConditionalOnProperty(value = "spring.cache.type", havingValue = "redis")
@Configuration(proxyBeanMethods = false)
public class RedisCacheAutoConfiguration {
@ConditionalOnMissingBean(CacheManager.class)
@Bean
public RedisCacheManager redisCacheManager(CacheSpecBuilder cacheSpecBuilder, RedisConnectionFactory redisConnectionFactory) {
Map cacheConfigurations = new HashMap<>();
cacheSpecBuilder.getSpecs().forEach((s, cacheSpec) -> cacheConfigurations.put(s, RedisCacheConfiguration.defaultCacheConfig().prefixCacheNameWith("cache:").entryTtl(cacheSpec.getExpireTime())));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().prefixCacheNameWith("dc:cache:").entryTtl(cacheSpecBuilder.getExpireTime()))
.withInitialCacheConfigurations(cacheConfigurations)
.build();
}
@ConditionalOnMissingBean(CacheHelper.class)
@Bean
public DefaultCacheHelper defaultCacheHelper(RedisCacheManager redisCacheManager){
return new DefaultCacheHelper(redisCacheManager);
}
}