【问题标题】:Python: No connection could be made because the target machine actively refused itPython:无法建立连接,因为目标机器主动拒绝它
【发布时间】:2017-06-01 02:55:33
【问题描述】:

我有一个多线程 python 程序,它会不断打开与本地 URL 的连接(http://testing.com/sendMessages_mock.php),我已经安装了 WAMP 并在本地有 sendMessages_mock.php 文件用于测试目的。有时,我得到“[Errno 10061] 无法建立连接,因为目标机器主动拒绝它”

每个线程都会调用这个函数。每一秒,就会有数百个线程调用这个函数。仅针对少数线程调用获取此异常。对此有什么想法吗?

def sendMessage(body):
    try:
        request = Request(url="http://testing.com/sendMessages_mock.php", data=json.dumps(body))
        request.add_header('Authorization', 'key=' + CONST.API_KEY)
        request.add_header('Content-Type', 'application/json')
        response = urlopen(request)
        responseData = response.read().decode('utf-8')

    except Exception as exceptionErr:
        print("Oops! " + str(traceback.format_exc()))

【问题讨论】:

  • 服务器端侦听连接,但listen 调用有一个积压 - 尚未接受的传入连接请求的最大数量。当该请求队列太大时,服务器 TCP 堆栈可能会开始拒绝连接。这可能就是你所看到的。您可能可以将服务器配置为更大的积压,但也要考虑到这是正常的背压,告诉您的客户冷静一点。

标签: python multithreading python-2.7 python-multithreading urlopen


【解决方案1】:

如果每秒调用过多是导致 WAMP 拒绝请求的问题,并且您希望在 Python 端解决此问题,则可以编写限制器类来处理 sendMessage 执行并限制调用次数。

请注意,这是我对别人问题的第一个回答,因此可能是绝对错误的。请保持合理的怀疑态度。

#python 2.7
import threading

class Throttle(object):
    def __init__(self, call_limit, interval):
        self.call_limit = call_limit
        self.interval = interval
        self.cleaner = None
        self.buffer = threading.Semaphore(call_limit)
        self.calls_in_buffer = 0

    def call(self, function, *args):
        self.buffer.acquire()

        self.calls_in_buffer += 1
        try:
            return function(*args)
        except:
            raise
        finally:
            if self.cleaner == None:
                self._init_cleaner()

    def _drain(self):
        for i in range(self.call_limit):
            self.calls_in_buffer -= 1
            self.buffer.release()
        self.cleaner = None

    def _init_cleaner(self):
        self.cleaner = threading.Timer(self.interval, self._drain)
        self.cleaner.daemon = True
        self.cleaner.start()

通过此类调用将有效地限制请求,因此服务器将能够处理它们。

【讨论】:

  • 假设这可行,它可能会更好作为decorator。在这种情况下,它将接受将函数包装在其构造函数中,并且call 将被替换为__call__。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 2023-03-25
  • 2017-05-13
  • 2015-04-05
  • 2016-12-08
  • 2014-09-05
相关资源
最近更新 更多