2

我有一个基于 twisted.internet.protocol.ReconnectingClientFactory 的客户端。当达到当前服务器的重试次数时,我希望这个客户端切换到不同的服务器;我连接到server1,失败5次,我切换到server2

我目前已经通过在重连工厂的重试功能中更改目标主机和端口来实现这一点:

class Factory(twisted.internet.protocol.ReconnectingClientFactory, object):

    def retry(self, connector=None):
    """ Retry to connect to the host. After the Max retries count is reached, 
    switch to an alternative host if available """

    if connector is None:
        if self.connector is None:
            raise ValueError("no connector to retry")
        else:
            connector = self.connector


    if self.retries >= self.maxRetries and self.alt_host is not None:
        # Try to connect to alternate server
        currrent_host, current_port = connector.host, connector.port
        connector.host, connector.port = self.alt_host, self.alt_port
        self.alt_host, self.alt_port = currrent_host, current_port
        print ("Switching to server: %s:%s" % (connector.host, connector.port))
        # Connector gets new address
        connector.getDestination() 
        # reset number of retries
        self.resetDelay()                

    super(Factory, self).retry(connector)

    def addHost(self, host, port):
         """ Add a second host/port to try to connected to once max number of retries has been done"""
        self.alt_host = host
        self.alt_port = port

我这样称呼这段代码:

factory = Factory()
reactor.connectTCP(self.host, self.port, factory)
factory.addHost(self.alt_host, self.alt_port)

这并不令人满意,因为我必须将第二台服务器的地址发送给工厂。我正在寻找基于第二个 reactor.connectTCP() 调用或更好地使用扭曲机制(延迟?)的不同解决方案。

4

0 回答 0