【问题标题】:Twisted: ReconnectingClientFactory connection to different serversTwisted: ReconnectingClientFactory 连接到不同的服务器
【发布时间】:2012-12-24 16:26:22
【问题描述】:

我有一个扭曲的 ReconnectingClientFactory,我可以通过这个工厂成功连接到给定的 ip 和端口对。而且效果很好。

reactor.connectTCP(ip, port, myHandsomeReconnectingClientFactory)

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

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

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

【问题讨论】:

    标签: python python-2.7 twisted failover


    【解决方案1】:

    我试试类似的东西:

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

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

    【讨论】:

    • hostport 都不是 IConnector 的公共属性。由于在 Twisted 的未来版本中允许的、兼容的更改,此解决方案可能会失败。
    【解决方案2】:

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

    您也可以尝试将其构建为端点(这是一些人喜欢的较新的高级连接设置 API),但处理与端点的重新连接还不是一个有据可查的主题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多