我正在从单节点 Redis 切换到基于哨兵的多节点 Redis 实例,并且由于新实例的 VCAP 结构不同并且默认情况下不由 Spring 处理,我知道我们需要自己解析 VCAP 并配置Redis bean。
遵循 Spring 文档 here ,这就是我调整 Redis bean 的方式:
public RedisConnectionFactory jedisConnectionFactory(JsonArray sentinelNodes) {
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration().master("mymaster");
String hostname;
String port;
for (int i = 0; i < sentinelNodes.size(); i++) {
JsonObject sentinelNode = sentinelNodes.getJsonObject(i);
hostname = sentinelNode.getString("hostname");
port = sentinelNode.getString("port");
sentinelConfig.sentinel(hostname, Integer.parseInt(port));
}
return new JedisConnectionFactory(sentinelConfig);
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
JsonArray sentinelNodes = environmentHandler.getSentinelNodesForRedis();
if (sentinelNodes != null) {
cf = jedisConnectionFactory(sentinelNodes);
}
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(cf);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
return redisTemplate;
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
return new RedisCacheManager(redisTemplate);
}
我从 VCAP 获取哨兵节点的信息并将其传递以创建我的 JedisConnectionFactory。我能够像这样配置 bean,但在运行时收到异常,指出 'org.springframework.data.redis.RedisConnectionFailureException:无法获取 Jedis 连接;嵌套异常是 java.lang.NullPointerException:在尝试调用从局部变量 'shardInfo' 加载的空对象的方法 redis.clients.jedis.JedisShardInfo.getHost() 时 |在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:204)...”。据我了解,我使用 RedisSentinelConfiguration 而不是 JedisShardInfo 配置了 JedisConnectionFactory,我不应该需要 shardInfo。
在检查这个库的较新版本时,我注意到这个特定的代码被修改为 this .所以我适应了这个较新的版本,但现在应用程序在启动期间崩溃并出现以下异常。
java.lang.NoSuchMethodError:org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V |在 org.springframework.data.redis.connection.RedisStandaloneConfiguration.(RedisStandaloneConfiguration.java:61) |在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.(JedisConnectionFactory.java:99) |在 org.springframework.data.redis.connection.jedis.JedisConnectionFactory.(JedisConnectionFactory.java:111)...
以下异常带走了我 here , 但我不明白为什么会导致此异常。
有人能指出我哪里出错了,或者给我指出如何通过 Spring Boot bean 配置这些多节点 Redis sentinel 的示例吗?
最佳答案
在返回 RedisConnectionFactory 之前调用 afterPropertiesSet() 方法似乎已经成功了。
(另外,设置了Factory的密码。)
关于spring - 在 CloudFoundry 上为 Redis 实例配置哨兵节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47034620/