LoginSignup
2
3

More than 5 years have passed since last update.

綺麗に止まられるRedisのSubscriber

Posted at

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

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3