Issue
I want to connect to redis by using SSL. I set up host, port etc. but when i'm setting...
spring.redis.ssl=true
and when i run the application i got following error:
org.springframework.data.redis.RedisConnectionFailureException:
Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to
XXX:XXX at
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory$ExceptionTranslatingConnectionProvider.translateException(LettuceConnectionFactory.java:1689) ~[spring-data-redis-2.5.7.jar:2.5.7]Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[na:na] at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:349) ~[na:na]
Actually my certificate (test.pem) is in resources folder in spring boot apllication project. Where should i put the certificate file or how to set the path to this file? I want to set it by application.yml or by java code.
Solution
This configuration works in my case:
@Configuration
@RequiredArgsConstructor
public class RedisSSLConfiguration {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.ssl:false}")
private boolean sslEnabled;
private final ResourceLoader resourceLoader;
@Bean
RedisConnectionFactory redisConnectionFactory() throws IOException {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setPassword(password);
LettuceClientConfiguration.LettuceClientConfigurationBuilder lettuceClientConfigurationBuilder =
LettuceClientConfiguration.builder();
if (sslEnabled){
SslOptions sslOptions = SslOptions.builder()
.trustManager(resourceLoader.getResource("classpath:redis.pem").getFile())
.build();
ClientOptions clientOptions = ClientOptions
.builder()
.sslOptions(sslOptions)
.protocolVersion(ProtocolVersion.RESP3)
.build();
lettuceClientConfigurationBuilder
.clientOptions(clientOptions)
.useSsl();
}
LettuceClientConfiguration lettuceClientConfiguration = lettuceClientConfigurationBuilder.build();
return new LettuceConnectionFactory(redisStandaloneConfiguration, lettuceClientConfiguration);
}
}
Answered By - Alchemisz
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)