serverFind.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import time
  2. from concurrent.futures import ThreadPoolExecutor
  3. import requests
  4. from .ipFind import ipFind # 假设ipFind是一个从本地模块导入的函数
  5. def task(i):
  6. """发送HTTP请求检查服务器状态的任务函数"""
  7. #sleep_seconds = random.uniform(0, 0.1)
  8. #print(sleep_seconds)
  9. # 可选:取消注释以显示线程执行信息
  10. # print('线程名称:{},参数:{},睡眠时间:{}'.format(threading.current_thread().name, i, sleep_seconds))
  11. try:
  12. # 随机延迟,减少请求风暴
  13. #time.sleep(sleep_seconds)
  14. # 发送请求并设置合理的超时时间
  15. r = requests.get(f'http://{i}:5001/findserver', timeout=0.5, headers={'Content-Type': 'application/json'})
  16. r = r.json()['msg']
  17. print(r)
  18. except requests.exceptions.ConnectTimeout:
  19. # 连接超时处理
  20. r = '0'
  21. except requests.exceptions.ReadTimeout:
  22. # 读取超时处理
  23. r = '0'
  24. except requests.exceptions.ConnectionError:
  25. # 连接错误处理
  26. r = '0'
  27. except Exception as e:
  28. # 其他异常处理
  29. #print(f"请求处理异常: {e}")
  30. r = '0'
  31. return [i, r]
  32. def findServer():
  33. """查找可用服务器的主函数"""
  34. time1 = time.time()
  35. # 创建线程池,设置合理的最大工作线程数
  36. with ThreadPoolExecutor(max_workers=500) as pool:
  37. # 获取所有IP地址
  38. allIP = ipFind()
  39. # 使用线程池并行执行任务
  40. result = list(pool.map(task, allIP))
  41. #print(f'耗时:{time.time() - time1}')
  42. # 筛选可用服务器
  43. serverList = []
  44. for item in result:
  45. if "天府综合平台一期:" in item[1]:
  46. item[1] = item[1].replace("天府综合平台一期:", "")
  47. serverList.append(item)
  48. return serverList
  49. if __name__ == '__main__':
  50. l = findServer()
  51. #print("可用服务器列表:", l)