1 | initial version |
To set up Redis Sentinel in Micronaut, follow these steps:
lettuce-core
and lettuce-sentinel
dependencies to your project:implementation("io.lettuce:lettuce-core:5.3.5.RELEASE")
implementation("io.lettuce:lettuce-sentinel:5.3.5.RELEASE")
RedisSentinelClient
bean in your Micronaut application:@Singleton
public class RedisSentinelClient {
private final RedisURI redisUri;
private final RedisClient redisClient;
private final StatefulRedisSentinelConnection<String, String> connection;
public RedisSentinelClient(
@Value("${redis.sentinel.master-name}") String masterName,
@Value("${redis.sentinel.nodes}") String nodes
) {
redisUri = RedisURI.Builder.sentinel(nodes, masterName).build();
redisClient = RedisClient.create(redisUri);
connection = redisClient.connectSentinel();
}
public StatefulRedisConnection<String, String> getConnection() {
return connection.master();
}
@PreDestroy
public void close() {
redisClient.shutdown();
}
}
This bean initializes a RedisSentinelClient
with the masterName
and nodes
properties, which should be set in your application configuration. The getConnection()
method returns a StatefulRedisConnection
to the master Redis instance.
RedisSentinelClient
in your Micronaut application. For example, you can inject it into a controller:@Controller("/example")
public class ExampleController {
private final RedisSentinelClient redisSentinelClient;
public ExampleController(RedisSentinelClient redisSentinelClient) {
this.redisSentinelClient = redisSentinelClient;
}
@Get("/{id}")
public String getById(@PathVariable("id") Long id) {
StatefulRedisConnection<String, String> connection = redisSentinelClient.getConnection();
RedisCommands<String, String> commands = connection.sync();
String value = commands.get(id.toString());
connection.close();
return value;
}
}
This controller injects the RedisSentinelClient
and uses it to get a StatefulRedisConnection
to the master Redis instance. It then uses the RedisCommands
API to get a value from Redis and closes the connection.
That's it! You now have a Micronaut application set up with Redis Sentinel.