1

We are using Lettuce in our project. We have a requirement to monitor the status of connection.

I know Lettuce can re-connect Redis when the connection is down. But is there some way to notify application that the connection is down/up?

Thanks, Steven

Steven.Niu
  • 11
  • 3

1 Answers1

1

Lettuce provides an event-model for connection events. You can subscribe to the EventBus and react to events published on the bus. There are multiple events, but for your case, you'd want to listen to connected and disconnected events:

  • ConnectionActivatedEvent: The logical connection is activated and can be used to dispatch Redis commands (SSL handshake complete, PING before activating response received)
  • ConnectionDeactivatedEvent: The logical connection is deactivated. The internal processing state is reset and the isOpen() flag is set to false.

Both events are fired after receiving Transport-related events such as ConnectedEvent respective DisconnectedEvent.

The following example illustrates how to consume these events:

RedisClient client = RedisClient.create()
EventBus eventBus = client.getresources().eventBus();

Disposable subscription = eventBus.get().subscribe(e -> {

    if (e instanceOf ConnectionActivatedEvent) {
        // …
    }
});

…
subscription.dispose();
client.shutdown();

Please note that events are dispatched asynchronously. Anything that happens in the event listener should be non-blocking (i.e. if you need to call blocking code such as further Redis interaction, please offload this task to a dedicated Thread).

Read more

mp911de
  • 17,546
  • 2
  • 55
  • 95
  • In case when Redis Sentinel is used and all servers are down, ConnectionWatchdog starts trying to access the sentinels and connect to last known destinations of the servers. During this time, ConnectedEvent, ConnectionActivatedEvent, DisconnectedEvent and ConnectionDeactivatedEvent are notified both for Sentinels and servers (when they are finally reconnected to). How can I understand whether the ConnectionActivatedEvent is from the server and not a sentinel? Judging by port is not reliable. – Inego Sep 18 '20 at 13:08
  • Related question: why is there a dedicated event `ReconnectFailedEvent`, but no event for successful reconnection, although the fact of successful reconnection is properly logged? – Inego Sep 18 '20 at 13:16
  • Because a failed Reconnect can be detected. A connection established signal is emitted from the general connection mechanism that receives a connect event without knowing the origin (and we can't attach an origin since these are netty internals). – mp911de Sep 21 '20 at 07:11
  • Posted a separate question (related but mostly concerning Spring): https://stackoverflow.com/q/63986017/1644036 – Inego Sep 21 '20 at 08:26