2

我开始我的扭曲应用程序:

application = twisted.application.service.Application('myserv')
my_service = MyService()
my_service.setServiceParent(application)
my_factory = twisted.internet.protocol.ServerFactory()
my_factory.protocol = MyProtocol
twisted.application.internet.TCPServer(port, my_factory).setServiceParent(application)

class MyService:
    def startService(self):
        #only synchronous code here?

在此服务可以接受客户端 tcp 连接之前,我需要建立与 redis 服务器的连接,这涉及到异步代码的执行。我想使用d=txredisapi.Connection()d = yield txredisapi.Connection()inlineCallbacks. 这个 deferred 必须在服务启动之前触发(在客户端的 tcp 连接被接受之前)。启动的最佳地点是txredisapi.Connection()什么?理想情况下,我想把它放在MyService课堂上。

4

1 回答 1

1

只需在顶层编写函数来创建 Redis 连接并将其传递给 MyService。可以在异步代码中添加服务。

application = twisted.application.service.Application("myserv")

@defer.inlineCallbacks
def startApp():
  rc = yeld txredisapi.Connection()
  my_service = MyService(rc)
  my_service.setServiceParent(application)
  my_factory = twisted.internet.protocol.ServerFactory()
  my_factory.protocol = MyProtocol
  twisted.application.internet.TCPServer(port, my_factory).setServiceParent(application)

startApp()
于 2013-04-25T04:48:52.847 回答