Skip to content

Commit 6dd2801

Browse files
Merge pull request #2416 from redis/DOC-5964-python-custom-failback
DOC-5964 redis-py custom failover callback example
2 parents 2570212 + 5468e4e commit 6dd2801

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

content/develop/clients/redis-py/failover.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,56 @@ There are also a few other options you can pass to the `MultiDbConfig` construct
202202
| `failover_attempts` | Number of attempts to fail over to a new endpoint before giving up. Default is `10`. |
203203
| `failover_delay` | Time interval between successive failover attempts. Default is `12` seconds. |
204204
| `auto_fallback_interval` | Time interval between automatic failback attempts. Default is `30` seconds. |
205+
| `event_dispatcher` | `EventDispatcher` object to use for emitting events. Supply this to register custom event listeners (see [Failover callbacks](#failover-callbacks) below for more information). |
206+
207+
### Failover callbacks
208+
209+
You may want to take some custom action when a failover occurs. For example, you could log a warning, increment a metric, or externally persist the cluster connection state.
210+
211+
You can implement a custom event listener using a class that implements `EventListenerInterface`. This includes a `listen()` method that is called when
212+
the event occurs. You should specifically listen for the `ActiveDatabaseChanged`
213+
event, which is emitted when a failover happens.
214+
215+
The example below shows how to implement a simple listener class and register an instance
216+
of it using an `EventDispatcher` object. You can then pass the `EventDispatcher` to the
217+
`MultiDbConfig` constructor to enable the custom behavior.
218+
219+
```py
220+
import logging
221+
222+
from redis.multidb.client import MultiDBClient
223+
from redis.multidb.config import MultiDbConfig
224+
225+
from redis.event import EventListenerInterface, EventDispatcher
226+
from redis.multidb.event import ActiveDatabaseChanged
227+
...
228+
229+
class LogFailoverEventListener(EventListenerInterface):
230+
def __init__(self, logger: logging.Logger):
231+
self.logger = logger
232+
233+
def listen(self, event: ActiveDatabaseChanged):
234+
self.logger.warning(
235+
f"Failover happened. Active database switched from {event.old_database} to {event.new_database}"
236+
)
237+
238+
event_dispatcher = EventDispatcher()
239+
listener = LogFailoverEventListener(logging.getLogger(__name__))
240+
241+
# Register custom listener
242+
event_dispatcher.register_listeners(
243+
{
244+
ActiveDatabaseChanged: [listener],
245+
}
246+
)
247+
248+
config = MultiDbConfig(
249+
event_dispatcher=event_dispatcher,
250+
...
251+
)
252+
253+
client = MultiDBClient(config)
254+
```
205255

206256
## Health check strategies
207257

0 commit comments

Comments
 (0)