Python-twisted客户端连接故障转移

时间:2013-12-20 08:03:49

标签: twisted failover

我正在编写一个带有Twisted框架的tcp代理,需要一个简单的客户端故障转移。如果代理无法连接到一个后端,则连接到列表中的下一个。我用了 reactor.connectTCP(host, port, factory)代理,直到我完成此任务,但如果无法连接,它不会吐出错误。如何捕获,它无法连接并尝试其他主机,还是应该使用其他连接方法?

1 个答案:

答案 0 :(得分:0)

您可以使用延迟来执行此操作

class MyClientFactory(ClientFactory):

    protocol = ClientProtocol

    def __init__(self, request):
        self.request = request
        self.deferred = defer.Deferred()

    def handleReply(self, command, reply):
        # Handle the reply
        self.deferred.callback(0)

    def clientConnectionFailed(self, connector, reason):
        self.deferred.errback(reason)

def send(_, host, port, msg):
    factory = MyClientFactory(msg)
    reactor.connectTCP(host, port, factory)
    return factory.deferred

d = Deferred()
d.addErrback(send, host1, port1, msg1)
d.addErrback(send, host2, port2, msg2)
# ...
d.addBoth(lambda _: print "finished")

如果第一个错误发生,这将触发下一个错误,否则转到打印功能。