python redis pubsub阻塞

标签 python redis-py

import redis
import threading

class Listener(threading.Thread):
    def __init__(self, r, channel):
        threading.Thread.__init__(self)
        self.redis = r
        self.pubsub = self.redis.pubsub()
        self.pubsub.subscribe(channel)

def run(self):
    for item in self.pubsub.listen():
        # do stuff
        pass

在上面的代码中我如何停止线程?

下面我有一个示例代码向您展示我想要什么:

class Listener(threading.Thread):
    def __init__(self, r, channel):
        threading.Thread.__init__(self)
         self.redis = r
         self.pubsub = self.redis.pubsub()
         self.pubsub.subscribe(channel)
         self.stop = False

    def run(self):
        while not stop:
            # get item from channel

因此,当属性 stop == True 时,线程将退出循环并结束。 那可能吗?如果不是,还有哪些替代方案?

最佳答案

有一个有用的要点展示了如何传递一个命令来打破循环并取消订阅。这可能有助于了解如何以其他方式做到这一点。

for item in self.pubsub.listen():
    if item['data'] == "KILL":
        self.pubsub.unsubscribe()
        print self, "unsubscribed and finished"
        break
    else:
        self.work(item)

您可以在此处查看示例代码:

关于python redis pubsub阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20175671/

相关文章:

python - 在安装构建依赖项之前检查 PyPI 上是否存在 Python 轮

c++ - 提取具有指定宽高比的子图像

python - 在 Python 3 中调用 super() 的 4 种方法中的哪一种?

python - 在 python 中,将 redis-py 与多处理模块一起使用,为什么每个进程都是不同的 fd?

python - 如何使用zscan以相反的顺序遍历Redis中的排序集?

python - 如何从 Node 服务器通知 python 客户端?

python - Google App Engine 上的异步 POST python 请求

python - 终止 PyQt 应用程序

python - redis-py 模块是否在集群模式下与 Redis 一起工作?