【发布时间】:2013-09-07 16:48:21
【问题描述】:
使用 Python、Twisted、Redis 和 txredisapi。
建立连接后如何获取订阅和取消订阅频道的订阅者协议?
我想我需要获取 SubscriberProtocol 的实例,然后我可以使用“订阅”和“取消订阅”方法,但不知道如何获取它。
代码示例:
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”关键字。然后你可以使用这个 deferred 来订阅和取消订阅。
在我的例子中,我忘记了 yield 关键字,所以 deferred 不完整,并且方法 suscribe 和 unsubscribe 不起作用。
【问题讨论】:
-
我试过你的代码,但是twisted抛出一个错误:exceptions.AttributeError: RedisListenerProtocol instance has no attribute 'factory' 然后我添加了__init__(self, factory) RedisListenerProtocol,它只给出了一个参数就会抛出另一个错误。也许一个简单而完整的代码会有所帮助。
标签: python redis twisted subscribe unsubscribe