Skip to content

Commit 06686cc

Browse files
committed
✨ feat: allow shutdown consume
1 parent 886e7d0 commit 06686cc

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/usepy_plugin_redis/__init__.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
import threading
23

34
import redis
45
import time
@@ -65,8 +66,19 @@ def connection(self):
6566
del self.state.connection
6667

6768

68-
class RedisStreamMixin:
69-
connection: redis.Redis
69+
class RedisStreamStore(RedisStore):
70+
71+
def __init__(self, *args, **kwargs):
72+
super().__init__(*args, **kwargs)
73+
self.__shutdown = False
74+
self.__shutdown_event = threading.Event()
75+
76+
def __del__(self):
77+
self.shutdown()
78+
79+
def shutdown(self):
80+
self.__shutdown = True
81+
self.__shutdown_event.set()
7082

7183
def _create_group(self, stream, group):
7284
try:
@@ -90,8 +102,12 @@ def send(self, stream, message, **kwargs):
90102

91103
def start_consuming(self, stream, group, consumer, callback, prefetch=1, **kwargs):
92104
"""开始消费"""
105+
self.__shutdown = False
106+
self.__shutdown_event.clear()
93107
self._create_group(stream, group)
94-
while True:
108+
while not self.__shutdown:
109+
if self.__shutdown:
110+
break
95111
try:
96112
messages = self.connection.xreadgroup(group, consumer, {stream: '>'}, count=prefetch, **kwargs)
97113
for message in messages:
@@ -107,9 +123,5 @@ def start_consuming(self, stream, group, consumer, callback, prefetch=1, **kwarg
107123
time.sleep(1)
108124

109125

110-
class RedisStreamStore(RedisStore, RedisStreamMixin):
111-
pass
112-
113-
114126
useRedis = RedisStore
115127
useRedisStreamStore = RedisStreamStore

0 commit comments

Comments
 (0)