在使用txredisapi建立连接后,订阅和取消订阅频道

时间:2013-09-04 08:56:11

标签: python redis twisted subscribe unsubscribe

使用Python,Twisted,Redis和txredisapi。

如何在连接完成后获取SubscriberProtocol以订阅和取消订阅频道?

我想我需要获取SubscriberProtocol的实例,然后我可以使用“subscribe”和“unsubscribe”方法,但不知道如何获取它。

代码示例:

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关键字,因此延迟不完整,方法中的订阅和取消订阅不起作用。

1 个答案:

答案 0 :(得分:0)

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