Python urllib3: 一段时间后关闭空闲连接

Python urllib3: close idle connection after some time

有没有办法告诉 Python urllib3 在一段时间后不要重用空闲连接,而是关闭它们?

https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool 中查找似乎没有显示任何相关内容。

首先,您可以定义 num_pools 变量,这样如果它超过了已创建的池的值,那么它将丢弃最近最少使用的池。您还可以在连接上设置 timeout ,以便连接可以在超时后自动关闭。我也找不到任何东西来确定空闲连接,但我想这可能会有所帮助

https://laike9m.com/blog/requests-secret-pool_connections-and-pool_maxsize,89/

记住:

A connection pool is a cache of database connections maintained so that the connections can be "reused" when future requests to the database are required.

你可以通过多种方式做到这一点(我猜):

  • 将重试次数设置为一次。

如果连接失败一次,就会中断您的连接。设置它:

import requests
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=1) # is zero for default
s.mount('http://', a)

  • 更改池连接。

"pool_connections" 是要保留的主机池的数量。例如,如果您要连接到 100 个不同的主机,并且 pool_connections=10,那么只会重新使用最新的 10 个主机的连接。要设置它:

s = requests.Session()
s.mount('https://', HTTPAdapter(pool_connections=1))
s.get('https://www.example.com')

这将停止重复使用池。


  • 池最大尺寸

只有在多线程环境下使用Session时才会关心这个。设置它:

s = requests.Session()
s.mount('https://', HTTPAdapter(pool_connections=1, pool_maxsize=1))

  • 配置最大尺寸

他 :class:~connectionpool.ConnectionPool class 保留了一个单独的池:class:~connection.HTTPConnection 实例。这些连接在单个请求期间使用,并在请求完成时返回到池中。默认情况下,只会保存一个连接以供重复使用。要设置它(默认情况下是):

from urllib3 import HTTPConnectionPool
pool = HTTPConnectionPool('www.example.com', maxsize=0) #likely to slow you down cuz it never stores the pools

maxsize – 要保存的可以重复使用的连接数。多于 1 在多线程情况下很有用。


  • 让泳池经理来做吧!

PoolManager 使用最近最少使用 (LRU) 策略来丢弃旧池。也就是说,如果你将 PoolManager num_pools 设置为 10,那么在向 11 个或更多不同的主机发出请求后,最近最少使用的池最终将被清理。所以要这样做:

from urllib3 import PoolManager
manager = PoolManager(1) # not the manager cleans up pools used for one time
r = manager.request('GET', 'http://www.example.com/')

另外,文档说:

Cleanup of stale pools does not happen immediately.

因此使用 RecentlyUsedContainer(文档仅包含一行)。

注:

Setting arguments if PoolManager affects all the pools connected thereby.


希望对您有所帮助。获取高级使用文档 HERE .