123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- import requests
- import time
- import random
- from concurrent.futures import ThreadPoolExecutor
- from .ipFind import ipFind # 假设ipFind是一个从本地模块导入的函数
- def task(i):
- """发送HTTP请求检查服务器状态的任务函数"""
- sleep_seconds = random.randint(1, 3)
- # 可选:取消注释以显示线程执行信息
- # print('线程名称:{},参数:{},睡眠时间:{}'.format(threading.current_thread().name, i, sleep_seconds))
- try:
- # 随机延迟,减少请求风暴
- time.sleep(sleep_seconds)
- # 发送请求并设置合理的超时时间
- r = requests.get(f'http://{i}:7162/findserver', timeout=3).text
- except requests.exceptions.ConnectTimeout:
- # 连接超时处理
- r = '0'
- except requests.exceptions.ReadTimeout:
- # 读取超时处理
- r = '0'
- except requests.exceptions.ConnectionError:
- # 连接错误处理
- r = '0'
- except Exception as e:
- # 其他异常处理
- print(f"请求处理异常: {e}")
- r = '0'
- return [i, r]
- def findServer():
- """查找可用服务器的主函数"""
- time1 = time.time()
- # 创建线程池,设置合理的最大工作线程数
- with ThreadPoolExecutor(max_workers=500) as pool:
- # 获取所有IP地址
- allIP = ipFind()
- # 使用线程池并行执行任务
- result = list(pool.map(task, allIP))
- print(f'耗时:{time.time() - time1}')
- # 筛选可用服务器
- serverList = []
- for item in result:
- if "天府综合平台一期:" in item[1]:
- item[1] = item[1].replace("天府综合平台一期:", "")
- serverList.append(item)
- return serverList
- if __name__ == '__main__':
- l = findServer()
- print("可用服务器列表:", l)
|