【问题标题】:Python-twisted client connection failoverPython 扭曲的客户端连接故障转移
【发布时间】:2014-01-09 00:52:32
【问题描述】:

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

【问题讨论】:

标签: twisted failover


【解决方案1】:

你可以使用 deferred 来做到这一点

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

如果第一个失败,这将触发下一个 errback,否则转到打印功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 2012-02-02
    • 2013-02-05
    • 1970-01-01
    • 2012-09-13
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多