如何用ThreadPoolExecutor限制服务器并发请求数
限制ThreadPoolExecutor并发请求数适配服务器能力
嘿,这个问题其实很容易解决!你只需要调整ThreadPoolExecutor的核心参数,再做个小优化就能完美匹配服务器的并发限制了。
核心修改点
- 设置正确的
max_workers值:这个参数直接控制同时运行的线程数,也就是同一时刻发起的请求数。你服务器最多能处理4个请求,所以把它设为4就可以了。 - 用
requests.Session优化请求:复用TCP连接能减少握手开销,提升整体请求效率,同时每个线程用独立的Session也能避免线程安全问题。
修改后的完整代码
import requests import concurrent.futures # 文件列表 files = [ r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_CanESM2_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_CNRM-CM5_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_CSIRO-Mk3-6-0_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_CCSM4_historical+rcp45_r2i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_MIROC5_historical+rcp45_r3i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_MPI-ESM-LR_historical+rcp45_r3i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_MRI-CGCM3_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_GFDL-ESM2G_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]', r'https://data.pacificclimate.org/data/downscaled_gcms/tasmin_day_BCCAQv2+ANUSPLIN300_HadGEM2-ES_historical+rcp45_r1i1p1_19500101-21001231.nc.nc?tasmin[0:55114][152:152][290:290]' ] # 与文件对应的气候模型名称列表 climate_model = ['CanESM2', 'CNRM-CM5','CSIRO-Mk3-6-0','CCSM4','MIROC5','MPI-ESM-LR','MRI-CGCM3','GFDL-ESM2G','HadGEM2-ES'] def min_function(url, model_name): # 使用Session复用TCP连接,提升请求效率且保证线程安全 with requests.Session() as session: r = session.get(url) # 主动检查请求是否成功,避免写入无效内容 r.raise_for_status() filename = f'tasmin85_{model_name}.nc' with open(filename, 'wb') as f: f.write(r.content) # 设置max_workers=4,严格限制同时发起的请求数 with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: executor.map(min_function, files, climate_model)
额外说明
max_workers的取值:这里设为4刚好匹配服务器的并发上限,如果你后续服务器能力调整,直接改这个数字就行。r.raise_for_status():这一步是可选但推荐的,当请求返回错误状态码时会抛出异常,方便你及时发现请求失败的情况,避免默默写入损坏的文件。- 线程安全:因为
requests.Session不是线程安全的,所以在每个函数调用里创建独立的Session实例,能避免多线程操作同一个Session导致的问题。
内容的提问来源于stack exchange,提问作者GrayLiterature




