如何以扭曲的工厂方法访问redis?

时间:2018-09-02 08:15:38

标签: redis twisted

我正在使用Redis来跟踪所有已连接的客户端/设备。套接字服务器用Twisted编写。由于redis的状态必须在运行套接字服务器之前进行初始化,并在从OS获得TERM信号后进行同步。我想实现两种工厂方法。

我尝试实现以下代码。但失败了。

\

从代码片段中,您可以看到我试图在两个工厂方法中添加代码:

  • startFactory()
  • stopFactory()

但是,如果我取消注释startFactory(),则@ defer.inlinecallbacks和yield会引发如下错误:

import txredisapi as redis
from twisted.internet import defer

conf = EpicConf().loadConf()
dbid = string.atoi(conf['Redisdbid'])
rcs =  redis.lazyConnection(password=conf['RedisPassword'], dbid=dbid, reconnect=True)
dbpool = adbapi.ConnectionPool("MySQLdb",db=conf['DbName'],user=conf['DbAccount'],\
        passwd=conf['DbPassword'],host=conf['DbHost'],\
        use_unicode=True,charset=conf['DbCharset'],cp_reconnect=True)

class PlainTCP(protocol.Protocol, TimeoutMixin):
    global conf

    def __init__(self, factory):
        self.factory = factory

class PlainTCPFactory(protocol.Factory):
    global conf
    onlineDevices = 'GlinkOnlineDevices'
    timezone = 8 # for CST +8

    def __init__(self):
        global conf
        print "Info: Version={}, TimeOutIdle={}".format(__version__, conf['TimeOutIdle'])

    def buildProtocol(self, addr):
        return PlainTCP(self)

    #@defer.inlineCallbacks
    def startFactory(self):
        #global rcs
        print "beforeRunning(): clean redis for running"
        #yield rcs.delete(self.onlineDevices)

    #@defer.inlineCallbacks
    def stopFactory(self):
        #global rcs
        print "afterRunning(): load from redis for logging"
        #yield rcs.delete(self.onlineDevices)

def main():
    #or another init redis operations here
    reactor.listenTCP(6000, PlainTCPFactory(), interface="0.0.0.0")
    reactor.run
    #or another sync redis operations here

if __name__ == "__main__":
    main()

如果我取消注释stopFactory()并引发以下错误。

        Traceback (most recent call last):
          File "/usr/local/lib/python2.7/dist-packages/Twisted-15.0.0-py2.7-linux-i686.egg/twisted/internet/defer.py", line 1107, in _inlineCallbacks
            result = g.send(result)
          File "EpicGlinkTcpServer.py", line 887, in startFactory
            yield rcs.delete(self.onlineDevices)
          File "/usr/local/lib/python2.7/dist-packages/txredisapi-1.2-py2.7.egg/txredisapi.py", line 1698, in wrapper
            d = self._factory.getConnection()
          File "/usr/local/lib/python2.7/dist-packages/Twisted-15.0.0-py2.7-linux-i686.egg/twisted/internet/defer.py", line 1253, in unwindGenerator
            return _inlineCallbacks(None, gen, Deferred())
        --- <exception caught here> ---
          File "/usr/local/lib/python2.7/dist-packages/Twisted-15.0.0-py2.7-linux-i686.egg/twisted/internet/defer.py", line 1107, in _inlineCallbacks
            result = g.send(result)
          File "/usr/local/lib/python2.7/dist-packages/txredisapi-1.2-py2.7.egg/txredisapi.py", line 2037, in getConnection
            raise ConnectionError("Not connected")
        txredisapi.ConnectionError: Not connected

我不知道如何在此处实现正确的代码。我还有两个选择。

  1. 添加另一个syncuns redis库,无论当前的txredisapi如何,都在main()中添加两个代码。
  2. 在外部bash shell脚本中添加脚本。

但是,如果有人可以帮助我实现工厂方法。那将是完美的。

谢谢。

1 个答案:

答案 0 :(得分:0)

请查看以下示例,我认为它可以为您提供帮助。

redis.py

import txredis
from twisted.internet import protocol, reactor

REDIS = None
HOST = "localhost"
PORT = 6379

# Making connection ##############################################
def create_connection():
    client_creator = protocol.ClientCreator(reactor, txredis.RedisClient)
    df = client_creator.connectTCP(HOST, PORT)
    df.addCallback(connection_success)
    df.addErrback(cannot_connect)

# connection created
def connection_success(redis_protocol):
    global REDIS
    REDIS = redis_protocol

def cannot_connect(error):
    print(error)


def getRedis():
    global REDIS
    return REDIS

create_connection()`

main.py

from twisted.internet.protocol import ServerFactory, Protocol
from twisted.internet import reactor

from redis import getRedis


class MyProtocol(Protocol):

    def connectionMade(self):
        print(self)


class MyFactory(ServerFactory):

    protocol = MyProtocol
    onlineDevices = 'GlinkOnlineDevices'

    def __init__(self):
        pass

    def buildProtocol(self, addr):
        print(getRedis())
        p = self.protocol()
        p.factory = self
        return p

    def startFactory(self):
        def success(result):
            print(result)

        def gotError(error):
            print(error)

        redis = getRedis()
        df = redis.delete(self.onlineDevices)
        df.addCallback(success)
        df.addErrback(gotError)

    def stopFactory(self):
        redis = getRedis()

def startService():
    reactor.listenTCP(6000, MyFactory())

reactor.callLater(2, startService)
reactor.run()

2秒后,我在这里开始出厂,以在工厂初始化之前建立redis连接。

为方便起见,我建议不要在工厂中访问Redis对象,而可以在Redis类中添加所需的方法,以在Redis数据库中执行操作。

我希望这可以为您提供帮助。

好运。