我有2个jedis缓存:
其中一个redis实例在本地托管,另一个在具有密码的安全计算机上托管。我有一个Spring Boot配置类。
public class RedisCacheConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
CacheManager cacheManager() {
return new RedisCacheManager(redisTemplate());
}
}
在我的application.yml
文件中,如何修改spring.redis.cluster
选项以包含多个节点,一个包含密码?
我正在使用Jedis 1.9.0。
答案 0 :(得分:1)
您可以根据需要创建任意数量的连接工厂,使用它们创建多个RedisTemplate
bean,然后创建多个CacheManager
bean:
@Configuration
@EnableConfigurationProperties
public class RedisCacheConfiguration {
public static class RedisProperties {
@NotNull @Size(min = 1) private List<String> nodes;
@NotNull private String password;
// getters and setters omitted
}
@ConfigurationProperties(prefix = "spring.redis.clusters")
@Validated
public static class MultipleRedisProperties {
@NotNull @Valid private RedisProperties local;
@NotNull @Valid private RedisProperties remote;
// getters and setters omitted
}
@Bean MultipleRedisProperties multipleRedisProperties() {
return new MultipleRedisProperties ();
}
@Bean JedisConnectionFactory localJedisCF() {
RedisClusterConfiguration clusterCfg = new RedisClusterConfiguration(redisProperties().getLocal().getNodes());
JedisConnectionFactory factory = new JedisConnectionFactory(clusterCfg );
factory.setPassword(redisProperties().getPassword());
factory.setUsePool(true);
return factory;
}
@Bean RedisTemplate<Object, Object> localRedisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(localJedisCF());
return redisTemplate;
}
@Bean CacheManager localJedisCacheManager() {
new RedisCacheManager(redisTemplate());
}
// similar bean definitions for the remote cluster omitted
}
然后,使用如下配置(YAML中的示例):
spring.redis.clusters:
local:
nodes: localhost:6379
password:
remote:
nodes: cache.servermachine.com:6380
password: abcdef
您可以将创建的缓存管理器用于缓存抽象:
@Cacheable(key = "#name", cacheManager = "localRedisCacheManager")
public String greet(@PathVariable String name) {
return "Hello " + name;
}
如果您使用的是Spring Data Redis,则可能必须排除以下自动配置:RedisAutoConfiguration
,RedisRepositoriesAutoConfiguration