我有一个使用密码运行的简单 Redis 服务器。我想通过我的 spring boot 应用程序与它交谈。我看here并看到有一个 spring.redis.password
所以我的 application-local.yml(使用 -Dspring.profiles.active=local
运行)看起来像...
spring:
redis:
password: ...
但是当我运行的时候我得到了
NOAUTH Authentication required
我错过了什么?我可以像...一样通过 node.js 进行连接
import redis from "redis";
const client = redis.createClient({
password: "..."
});
附加代码
@Bean
LettuceConnectionFactory redisConnectionFactory(){
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
return new LettuceConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
return template;
}
也试过...
@Bean
LettuceConnectionFactory redisConnectionFactory(){
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
if (redisPassword != null){
config.setPassword(redisPassword);
}
return new LettuceConnectionFactory(config);
}
这可行,但由于它是标准属性,所以看起来过于冗长。
最佳答案
如果您需要不那么冗长的配置,您可以从配置代码中删除 RedisConnectionFactory
bean,然后将 RedisConnectionFactory
bean 注入(inject)到您的 redisTemplate
中。 redisConnectionFactory
将使用 application.yml 中的属性进行填充:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
在这种情况下,Spring 默认注入(inject) LettuceConnectionFactory
。
问题出在这里:new RedisStandaloneConfiguration()
。如果您查看构造函数的代码,您会看到创建了空密码,并且除了调用 setter 之外无法设置它。
旧答案:您需要通过 RedisProperties
类从 application.yml
获取数据。试试这个:
@Bean
RedisConnectionFactory redisConnectionFactory(RedisProperties props) {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setPassword(props.getPassword());
return new LettuceConnectionFactory(config);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
这里 props
包含来自 spring.redis
部分的属性
关于java - 为什么我使用 Spring Boot 得到 "NOAUTH Authentication required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64775186/