2 years ago

#47017

test-img

Sidekick.John

Spring Boot + Lettuce + Redis-Sentinel without own beans?

In our Spring Boot-App, we are using Spring Data and Spring Cache together with Lettuce to connect to a REDIS-Cluster.
We are currently switching to a Sentinel-Connection-setup.

We are asking ourselves if there is another way to setup Lettuce/Redis-Sentinel than what we have come up with.

This works:
Excerpt from application.yml:

redis:
  sentinel:
    master: # master name does not matter
  port: # port still does not matter
  host: # hostname does not matter
  password: # password does not matter

Setting connect-timeout and timeout in application.yml does not suffice anymore. Because we define our own LettuceConnectionFactory-Bean. To be able to setup a RedisSentinelConfiguration.

Excerpt from CacheConfig.java:

@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
        .master(sentinelMaster)
        .sentinel(sentinelHost, Integer.valueOf(sentinelPort));
sentinelConfig.setPassword(RedisPassword.of(redisPassword));

SocketOptions socketOptions = SocketOptions.builder()
        .connectTimeout(Duration.ofSeconds(1L))
        .build();

ClientOptions clientOptions = ClientOptions.builder()
        .socketOptions(socketOptions)
        .timeoutOptions(TimeoutOptions.enabled())
        .build();

LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
        .commandTimeout(Duration.ofSeconds(1L))
        .clientOptions(clientOptions)
        .build();


return new LettuceConnectionFactory(sentinelConfig, lettuceClientConfiguration);
}

We use this LettuceConnectionFactory in our RedisCacheManager:

@Primary
@Bean
public RedisCacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory) {
return RedisCacheManager
        .RedisCacheManagerBuilder
        .fromConnectionFactory(lettuceConnectionFactory)
        .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.parse(defaultCacheTtl)))
        .build();
}

If it works, why bother?

What we liked before, was the option to set connect-timeout and timeout in our application.yml and have Spring Boot/Lettuce do the trick (setup LettuceConnectionFactory etc.) for us. We did not have to bother about other defaults and settings within this Connection.

So the question remains: Is there another way than providing a custom LettuceConnectionFactory-Bean to:

  • setup Lettuce using a RedisSentinelConfiguration
  • set both connect-timeout and timeout without all the builder() functions

For Example: Is it possible to setup another Bean (possibly a RedisSentinelConfiguration-Bean) which is then autowired during Autoconfiguration? Or is there a "config-only" approach (simply setting properties in application.yml)?

spring-boot

redis

lettuce

redis-sentinel

0 Answers

Your Answer

Accepted video resources