配置Redis作为Spring的缓存机制
@Configuration
@EnableRedisHttpSession
public class SpringCacheRedisConfig {
private Logger logger = LoggerFactory.getLogger(SpringCacheRedisConfig.class);
@Value("${redis.port}")
private Integer prot;
@Value("${redis.database}")
private Integer database;
@Value("${redis.hostname}")
private String hostname;
@Value("${redis.password}")
private String password;
@Value("${redis.cache.path}")
private String cachePath;
@Bean("standaloneConfiguration")
public RedisStandaloneConfiguration standaloneConfiguration() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setPort(prot);
configuration.setDatabase(database);
configuration.setHostName(hostname);
configuration.setPassword(RedisPassword.of(password));
return configuration;
}
@Bean("redisConnectionFactory")
public LettuceConnectionFactory redisConnectionFactory(@Qualifier("standaloneConfiguration") RedisStandaloneConfiguration configuration) {
return new LettuceConnectionFactory(configuration);
}
@Bean("springCacheManager")
public RedisCacheManager redisCacheManager(@Qualifier("redisConnectionFactory") RedisConnectionFactory factory) {
RedisCacheConfiguration defaultConfiguration = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheManagerBuilder builder = RedisCacheManager.builder(factory);
builder.withInitialCacheConfigurations(load(defaultConfiguration));
builder.cacheDefaults(defaultConfiguration);
return builder.build();
}
/** 加载缓存配置 */
protected Map<String, RedisCacheConfiguration> load(RedisCacheConfiguration defaultConfiguration) {
Map<String, RedisCacheConfiguration> configurations = new HashMap<>();
try {
Resource resource = ResourceUtil.getResource(cachePath);
if (resource != null && resource.exists()) {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Entry<Object, Object> entry : properties.entrySet()) {
Long seconds = Convert.toLong(entry.getValue(), 0L);
String key = Convert.toStr(entry.getKey(), null);
Duration ttl = Duration.ofSeconds(seconds);
logger.info("Load Cache configuration {} TTL is {} seconds.", key, seconds);
configurations.put(key, defaultConfiguration.entryTtl(ttl));
}
} else {
logger.warn("Not find cache configuration with {}", cachePath);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return configurations;
}
}
与之对应的redis.properties配置文件。
redis.port=6379
redis.database=0
redis.hostname=127.0.0.1
redis.password=
redis.cache.path=cache.properties
在上文中protected Map<String, RedisCacheConfiguration> load(RedisCacheConfiguration defaultConfiguration)
方法是为了在不修改java文件的基础上快速对各个缓存块配置失效时间,对应的配置文件为cache.properties。
eg:
shiro-authorizationCache=3360
shiro-authenticationCache=3360
网友评论