如果 HTTP 是无状态的,为什么我需要关闭数据库连接?
我在许多网络语言中看到的一个常见问题是数据库连接需要关闭,否则总连接数逐渐增加,然后以任何形式停止。
HTTP 是无状态的,当请求处理完成时,为什么这些语言不能直接删除请求打开的任何连接?是否有任何正当理由让您保持开放状态?
A commonly problem I see in lots of web languages is that database connections need to be closed otherwise the number of total connections gradually increases and then it grinds to a halt in whatever form.
HTTP is stateless, when the request has finished processing why can't these languages just drop any connections that request opened? Are there any legitimate reasons for why you might keep it open?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为打开、验证和授权访问数据库的成本相当昂贵。这就是为什么通常每个人都使用数据库连接池。当请求处理程序从池中获取可用的已打开连接时,连接仍然处于打开状态。当一个人关闭连接时,真正发生的是该连接被释放以供其他人使用。
来回答...
请求完成后,连接可能会保持打开状态并用于其他目的。例如数据的异步更新。但我同意你的观点,在 90% 的情况下,当请求完成时,打开的连接应该返回到池中。根据您使用的 Web 框架(Spring、DJANGO...),可以轻松配置或至少实现这种行为。
Because the cost of opening, authenticating and authorising access to a database is quite expensive. That is why normally everybody uses a databases connection pool. Connections are still open while request handlers pick up a available-already-opened connection from a pool. When one closes a connection what is really happening is that the connection is being freed for others to use.
To answer ...
Connections might stay opened after the request is complete and use for other purposes. For instance asynchronous updates of data. But I am with you, in 90% of the cases when the request is finished the connections opened should be returned back to the pool. Depending on the Web Framework you use (Spring, DJANGO, ...) this kind of behaviour can be configured or at least implemented with minimum effort.
在关闭 http 连接时检查打开的连接会产生更多开销,因此我想这就是为什么某些语言默认情况下不关闭它的原因。
如果您不显式关闭它,则必须由垃圾收集器来完成,这可能需要一段时间。
Checking for an open connection while closing an http connection gives more overhead so I guess that's why some languages don't close it by default.
And if you don't close it explicitly, it will have to be done by the garbage collector which can take a while.