在与 txredisapi 建立连接后订阅和取消订阅频道



Working with Python, Twisted, Redis and txredisapi.

建立连接后,如何获取订阅和取消订阅频道的订阅者协议?

我想我需要获取订阅者协议的实例,然后我可以使用"订阅"和"取消订阅"方法,但不知道如何获取它。

代码示例:

import txredisapi as redis
class RedisListenerProtocol(redis.SubscriberProtocol):
    def connectionMade(self):
        self.subscribe("channelName")
    def messageReceived(self, pattern, channel, message):
        print "pattern=%s, channel=%s message=%s" %(pattern, channel, message)
    def connectionLost(self, reason):
        print "lost connection:", reason
class RedisListenerFactory(redis.SubscriberFactory):
    maxDelay = 120
    continueTrying = True
    protocol = RedisListenerProtocol

然后从这些类之外:

# I need to sub/unsub from here! (not from inside de protocol)
protocolInstance = RedisListenerProtocol  # Here is the problem
protocolInstance.subscribe("newChannelName")
protocolInstance.unsubscribe("channelName")

有什么建议吗?

谢谢!


下一个代码解决了这个问题:

@defer.inlineCallbacks
def subUnsub():
    deferred = yield ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
    deferred.subscribe("newChannelName")
    deferred.unsubscribe("channelName")

解释:使用"ClientCreator"在带有标志"@defer.inlineCallbacks"的函数中获取SubscriberProtocol的实例,并且不要忘记等待完成延迟数据的"yield"关键字。然后,您可以使用此延迟来取消订阅。

就我而言,我忘记了 yield 关键字,因此延迟不完整,并且 suscribe 和取消订阅方法不起作用。

connecting = ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
def connected(listener):
    listener.subscribe("newChannelName")
    listener.unsubscribe("channelName")
connecting.addCallback(connected)

最新更新