为什么我在Spring Boot中获得“需要NOAUTH身份验证”?

时间:2020-11-10 19:04:53

标签: spring-boot redis

我有一个运行简单的Redis服务器并使用密码。我想通过我的Spring Boot应用程序与之交谈。我看着here,发现有一个spring.redis.password,所以我的application-local.yml(运行-Dspring.profiles.active=local)看起来像...

spring:
  redis:
    password: ... 

但是当我跑步时我会得到

需要NOAUTH身份验证

我想念什么?我可以通过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);
}

这是可行的,但由于它是标准属性,因此显得过于冗长。

1 个答案:

答案 0 :(得分:1)

如果您需要较少的详细配置,则可以从配置代码中删除RedisConnectionFactory bean,然后将RedisConnectionFactory bean注入您的redisTemplate中。 redisConnectionFactory将使用application.yml中的属性填充:

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}

在这种情况下,Spring默认情况下会注入LettuceConnectionFactory

问题出在这里:new RedisStandaloneConfiguration()。如果查看构造函数的代码,您会看到创建了空密码,除了调用设置器外,没有其他方法可以设置它。


旧答案:您需要从application.ymlRedisProperties类中获取数据。试试这个:

@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部分的属性