Issue
I have a simple redis server running with a password. I want to talk with it from my spring boot app. I look here and see there is a spring.redis.password
so my application-local.yml (running with -Dspring.profiles.active=local
) looks like...
spring:
redis:
password: ...
but when I run I get
NOAUTH Authentication required
What am I missing? I can connect via node.js like...
import redis from "redis";
const client = redis.createClient({
password: "..."
});
Additional Code
@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;
}
also tried...
@Bean
LettuceConnectionFactory redisConnectionFactory(){
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
if (redisPassword != null){
config.setPassword(redisPassword);
}
return new LettuceConnectionFactory(config);
}
and this works but seems overly verbose given it is a standard property.
Solution
If you need less verbose configuration, you can remove RedisConnectionFactory
bean from your configuration code and just inject the RedisConnectionFactory
bean in your redisTemplate
. redisConnectionFactory
will be populated with properties from application.yml:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
In this case, Spring injects LettuceConnectionFactory
by default.
The problem was here: new RedisStandaloneConfiguration()
. If you look at the code of constructor you will see that empty password is created and there is no way to set it besides calling a setter.
Old answer: You need to fetch your data from application.yml
through RedisProperties
class. Try this:
@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;
}
Here props
contains properties from spring.redis
section
Answered By - nkrivenko
Answer Checked By - Katrina (JavaFixing Volunteer)