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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何以扭曲的工厂方法访问redis?相关的知识,希望对你有一定的参考价值。

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

我尝试按如下方式实现代码。但失败了。

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()

但是如果取消注释startFactory(),@ defer.inlinecallbacks和yield将抛出如下错误:

        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

如果我取消注释stopFactory(),则抛出以下错误。

2018-09-02 16:11:24+0800 [BaseRedisProtocol,client] <twisted.internet.tcp.Connector instance at 0x9951e2c> will retry in 2 seconds
2018-09-02 16:11:24+0800 [BaseRedisProtocol,client] Stopping factory <txredisapi.RedisFactory instance at 0x9951dac>
2018-09-02 16:11:24+0800 [__main__.PlainTCPFactory] (TCP Port 6000 Closed)
2018-09-02 16:11:24+0800 [__main__.PlainTCPFactory] Stopping factory <__main__.PlainTCPFactory instance at 0x9962aac>
2018-09-02 16:11:24+0800 [__main__.PlainTCPFactory] afterRunning(): load from redis for logging
2018-09-02 16:11:24+0800 [__main__.PlainTCPFactory] Unhandled error in Deferred:
2018-09-02 16:11:24+0800 [__main__.PlainTCPFactory] Unhandled Error
        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 893, in stopFactory
            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. 添加另一个synchrouns redis库,无论当前的txredisapi如何,在main()中添加两个代码。
  2. 在外部bash shell脚本中添加脚本。

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

提前致谢。

答案

检查以下示例我认为它可以帮助您。

Redis.朋友

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()`

卖弄.朋友

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数据库中执行操作。

我希望这可以帮到你。

祝你好运。

以上是关于我如何以扭曲的工厂方法访问redis?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用javascript修复HTML画布对象中的扭曲/扭曲和剪切图像?

我可以/如何通过 websocket 连接到扭曲的应用程序访问客户端 cookie?

从意图活动访问片段方法

如何让旁遮普语/扭曲绕过 dns

如何将 View 类中的代码片段移动到 OnAppearing() 方法?

如何使用 html5 画布扭曲图像以创建在风中飘扬的旗帜效果