io.lettuce.core.RedisCommandException Exception:“NOAUTH Authentication required”
在某行工作,项目上线代码,uat环境无异常,上到pp环境有问题,报redis连接不上;
观察配置,发觉是apollo的配置是哨兵模式,有个哨兵密码。spring2.2.6RELEASE版本问题。于是写了全局配置,读取配置中的sentinel.password
package com.yupi.springbootinit.config;
import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Configuration
public class RedisConfig {
// 配置sentinel密码不生效,提示NOAUTH Authentication required。
//https://github.com/lettuce-io/lettuce-core/issues/1543
@Bean
public RedisSentinelConfiguration redisSentinelConfiguration(RedisProperties properties , @Value("${spring.redis.sentinel.password}") String sentinelPassword){
RedisProperties.Sentinel sentinelProperties = properties.getSentinel();
if (sentinelProperties != null) {
RedisSentinelConfiguration config = new RedisSentinelConfiguration();
config.master(sentinelProperties.getMaster());
config.setSentinels(createSentinels(sentinelProperties));
if (properties.getPassword() != null){
config.setPassword(RedisPassword.of(properties.getPassword()));
}
if (sentinelPassword != null) {
config.setSentinelPassword(RedisPassword.of(sentinelPassword));
}
config.setDatabase(properties.getDatabase());
return config;
}
return null;
}
private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>();
for (String node : sentinel.getNodes()) {
String[] split = StringUtils.split(node, ":");
Assert.notNull(split,"Must be defined as 'host:port'");
Assert.state(split.length==2,"Must be defined as 'host:port'");
nodes.add(new RedisNode(split[0],Integer.parseInt(split[1])));
}
return nodes;
}
}