原来:HTTP可以复用TCP连接

时间:2023-03-09 03:37:33
原来:HTTP可以复用TCP连接

问题

线上的一个项目会和微信服务器有API请求(目的是获取用户的微信信息),但会有偶发的报错:

'Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

原因是微信那边认为我频繁建立TCP连接是不对,很消耗他们的连接资源,所以把我的连接中断了。

概念

HTTP 的header里有一个“Keep-Alive”参数,用来告知服务器:我想要保存此次连接,我稍后还会请求,这样我们可以避免再次TCP三次握手。

python的requests库为我们提供了session来实现“Keep-Alive”,引入一段官方文档介绍:

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3’s connection pooling. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection).

结果

我使用requests库的session来管理我和微信服务器间的请求,确实再也没有过上面的报错。

扩展

保持存活(Keep Alive)不仅仅是HTTP中的概念,TCP中也有。不追究实现原理,单是它们所想达到的目的也是不同的:

  HTTP中叫做“Keep-Alive”, 是为了连接复用,即减少多余的TCP请求

  TCP中叫做“KeepAlive”,是为了保证连接是健康的,如即时通讯技术需要用到

相关文章