@@ -13,7 +13,9 @@ class RedisPubSubChannelLayer:
13
13
Channel Layer that uses Redis's pub/sub functionality.
14
14
"""
15
15
16
- def __init__ (self , hosts = None , prefix = "asgi" , ** kwargs ):
16
+ def __init__ (
17
+ self , hosts = None , prefix = "asgi" , on_disconnect = None , on_reconnect = None , ** kwargs
18
+ ):
17
19
if hosts is None :
18
20
hosts = [("localhost" , 6379 )]
19
21
assert (
@@ -22,6 +24,9 @@ def __init__(self, hosts=None, prefix="asgi", **kwargs):
22
24
23
25
self .prefix = prefix
24
26
27
+ self .on_disconnect = on_disconnect
28
+ self .on_reconnect = on_reconnect
29
+
25
30
# Each consumer gets its own *specific* channel, created with the `new_channel()` method.
26
31
# This dict maps `channel_name` to a queue of messages for that channel.
27
32
self .channels = {}
@@ -271,6 +276,7 @@ async def _get_sub_conn(self):
271
276
async with self ._lock :
272
277
if self ._sub_conn is not None and self ._sub_conn .closed :
273
278
self ._sub_conn = None
279
+ self ._notify_consumers (self .channel_layer .on_disconnect )
274
280
if self ._sub_conn is None :
275
281
if self ._receive_task is not None :
276
282
self ._receive_task .cancel ()
@@ -301,6 +307,7 @@ async def _get_sub_conn(self):
301
307
self ._receiver .channel (name ) for name in self ._subscribed_to
302
308
]
303
309
await self ._sub_conn .subscribe (* resubscribe_to )
310
+ self ._notify_consumers (self .channel_layer .on_reconnect )
304
311
return self ._sub_conn
305
312
306
313
async def _do_receiving (self ):
@@ -317,6 +324,11 @@ async def _do_receiving(self):
317
324
if channel_name in self .channel_layer .channels :
318
325
self .channel_layer .channels [channel_name ].put_nowait (message )
319
326
327
+ def _notify_consumers (self , mtype ):
328
+ if mtype is not None :
329
+ for channel in self .channel_layer .channels .values ():
330
+ channel .put_nowait (msgpack .packb ({"type" : mtype }))
331
+
320
332
async def _do_keepalive (self ):
321
333
"""
322
334
This task's simple job is just to call `self._get_sub_conn()` periodically.
0 commit comments