登录
原创

HTTP API请求的耗时优化

发布于 2024-08-26 阅读 447
  • Python
  • API
  • 性能优化
原创

HTTP请求的连接复用

‌HTTP请求的连接复用主要指的是在HTTP/1.1及以后的版本中,通过持久连接(Keep-Alive)和多路复用技术,允许在同一个TCP连接上发送和接收多个HTTP请求和响应。

日常工作中,某些场景下需要经常请求第三方提供的HTTP服务API。由于机房地域、网络线路、每次连接的创建与关闭的开销等因素,可能会造成请求响应耗时不是很理想。

其中一种优化方式,我们可以使用‌HTTP请求的连接复用,通过持久连接(Keep-Alive)和多路复用技术,在同一个TCP连接上发送多个请求,从而减少了建立新连接的次数,提高效率。(目前,大多数的HTTP库和Web服务器都支持Keep-Alive)

下面,我们通过Pythonrequests分别在连接复用和不复用的简单距离测试下耗时差异:

Python请求

1.普通请求,不用连接池

import time
import requests

# 使用普通请求, 不用连接池
url = 'https://apis.juhe.cn/mobile/get'
for i in range(10):
    ts = time.time()
    response = requests.get(url)
    te = time.time()
    print(f"普通请求:第{i}次请求,状态: {response.status_code}, 耗时: ", int(1000 * (te - ts)))

耗时情况:

普通请求:第0次请求,状态: 200, 耗时:  440
普通请求:第1次请求,状态: 200, 耗时:  366
普通请求:第2次请求,状态: 200, 耗时:  338
普通请求:第3次请求,状态: 200, 耗时:  381
普通请求:第4次请求,状态: 200, 耗时:  340
普通请求:第5次请求,状态: 200, 耗时:  327
普通请求:第6次请求,状态: 200, 耗时:  348
普通请求:第7次请求,状态: 200, 耗时:  358
普通请求:第8次请求,状态: 200, 耗时:  388
普通请求:第9次请求,状态: 200, 耗时:  348
普通请求:第10次请求,状态: 200, 耗时:  356
普通请求:第11次请求,状态: 200, 耗时:  330
普通请求:第12次请求,状态: 200, 耗时:  353
普通请求:第13次请求,状态: 200, 耗时:  356
普通请求:第14次请求,状态: 200, 耗时:  355
普通请求:第15次请求,状态: 200, 耗时:  343
普通请求:第16次请求,状态: 200, 耗时:  523
普通请求:第17次请求,状态: 200, 耗时:  490
普通请求:第18次请求,状态: 200, 耗时:  497
普通请求:第19次请求,状态: 200, 耗时:  350

2.http连接池,keepalive复用连接

import time
import requests

# 创建一个 Session 并挂载自定义的 HTTPAdapter
session = requests.Session()

# 使用http连接池, keepalive 复用连接
url = 'https://apis.juhe.cn/mobile/get'
for i in range(20):
    ts = time.time()
    response = session.get(url)
    te = time.time()
    print(f"普通请求:第{i}次请求,状态: {response.status_code}, 耗时: ", int(1000 * (te - ts)))

耗时情况:

http连接池:第0次请求,状态: 200, 耗时:  398
http连接池:第1次请求,状态: 200, 耗时:  108
http连接池:第2次请求,状态: 200, 耗时:  93
http连接池:第3次请求,状态: 200, 耗时:  99
http连接池:第4次请求,状态: 200, 耗时:  122
http连接池:第5次请求,状态: 200, 耗时:  90
http连接池:第6次请求,状态: 200, 耗时:  91
http连接池:第7次请求,状态: 200, 耗时:  92
http连接池:第8次请求,状态: 200, 耗时:  93
http连接池:第9次请求,状态: 200, 耗时:  89
http连接池:第10次请求,状态: 200, 耗时:  97
http连接池:第11次请求,状态: 200, 耗时:  101
http连接池:第12次请求,状态: 200, 耗时:  93
http连接池:第13次请求,状态: 200, 耗时:  92
http连接池:第14次请求,状态: 200, 耗时:  86
http连接池:第15次请求,状态: 200, 耗时:  122
http连接池:第16次请求,状态: 200, 耗时:  98
http连接池:第17次请求,状态: 200, 耗时:  99
http连接池:第18次请求,状态: 200, 耗时:  91
http连接池:第19次请求,状态: 200, 耗时:  96

通过比较上面两种请求方式的耗时,能很直观的看出连接复用情况下,耗时有明显的降低。但实际业务过程中,如果业务请求量很低,无法持续性进行,连接池可能无法长时间保持活跃,效果可能不会很明显,当然你也可以想办法去连接保活。

评论区

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0

举报