Question

I'm working in a project with Python, Twisted and Redis. So the team decided to use txredisapi for the communication between the Python modules and Redis. This project does a lot of different things and we need to subscribe to several channels for listen the messages sent by Redis without the other functionalities stops (asynchronously).

Can one execution handle all the work and listen the messages sent by Redis at the same time or must we separate and execute the code in differents flows?

We use the following code for listen the messages:

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

We try to listen the messages with:

self.connRedisChannels = yield redis.ConnectionPool()

I'm interested to know how can I specify that the Connection must use the "RedisListenerFactory", then I guess that the function "messageReceived" will be fired when a message arrives.

Any suggestions, example or correction will be apreciated.

Thanks!


The following code solves the problem:

from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor

defer = ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)

Thanks to Philippe T. for the help.

Was it helpful?

Solution

If you want to use directly the redis.Connection() may be you can do this before:

redis.SubscriberFactory.protocol = RedisListenerProtocol

the package make internal call to is factory for connection. other way is to rewrite *Connection class and make*Connection factory to use your factory.

to make the connection on other part of your code you can do something like this :

from twisted.internet.protocol import ClientCreator
from twisted.internet import reactor

# some where : 
defer = ClientCreator(reactor, RedisListenerProtocol).connectTCP(__HOST__, __PORT__)
# the defer will have your client when the connection is done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top