Twisted:重新连接到不同服务器的ClientFactory连接

时间:2013-01-10 10:08:08

标签: python python-2.7 twisted failover

我有一个扭曲的ReconnectingClientFactory,我可以成功连接到这个工厂给定的ip和端口。它运作良好。

  

reactor.connectTCP(ip,port,myHandsomeReconnectingClientFactory)

在这种情况下,当服务器消失时,myHandsomeReconnectingClientFactory会尝试连接相同的ip和端口(如预期的那样)。

我的目标是,当服务于给定的ip和端口对的服务器消失时,连接到备份服务器(具有不同的ip和端口)。

有关如何实现这一目标的任何想法/意见将不胜感激。

2 个答案:

答案 0 :(得分:3)

我尝试类似:

class myHandsomeReconnectingClientFactory(protocol.ReconnectingClientFactory):

    def __init_(self, hosts):
        # hosts should be a list of tuples (host, port)
        self._hosts = hosts

    def clientConnectionFailed(self, connector, reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def clientConnectionLost(self, connector, unused_reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def _try_next_host(self, connector):
        # round robing of servers
        to_try = self._hosts.pop(0)
        self._hosts.append(to_try)
        connector.host, connector.port = to_try
        self.connector = connector
        self.retry()

我实际上没有测试过它,但至少它应该给你一个很好的起点。好的。

答案 1 :(得分:2)

ReconnectingClientFactory没有此功能。您可以构建自己的工厂来实现这种重新连接逻辑,主要是通过挂钩clientConnectionFailed工厂方法。当调用它并且您认为合理切换服务器的原因(例如twisted.internet.error.ConnectionRefused)时,请选择列表中的下一个地址并使用适当的reactor.connectXYZ方法尝试连接它。

您也可以尝试将其构建为端点(这是某些人更喜欢的较新的高级连接设置API),但处理与端点的重新连接尚不是一个记录良好的主题。