PythonでThreadを起こしてRedisをSubscribeするとき
下記のように書いておけば、親スレッド停止時にstopを呼んであげるだけで綺麗に止められる。
class Subscriber():
def __init__(self):
self.stop_event = threading.Event()
kvs = redis.StrictRedis(host='localhost', port=6379, db=0)
self.pubsub = kvs.pubsub()
self.pubsub.subscribe('channel')
self.thread = threading.Thread(target=self.target)
self.thread.daemon = True
self.thread.start()
def target(self):
while not self.stop_event.is_set():
for message in self.pubsub.listen():
print(message)
def stop(self):
self.stop_event.set()
self.pubsub.unsubscribe()
self.thread.join()
ググっても、良いサンプルが無かったので書き残しておくのでした。
スレッド操作はxeno1991さんの記事を参考にしました。
https://qiita.com/xeno1991/items/b207d55a413664513e5f