gpt4 book ai didi

mysql - 一个mysql连接应该在golang中存活多长时间

转载 作者:IT王子 更新时间:2023-10-29 00:33:36 28 4
gpt4 key购买 nike

我正在使用带有 golang 的 mysql 并阅读此 doc .它说

Although it’s idiomatic to Close() the database when you’re finished with it, the sql.DB object is designed to be long-lived. Don’t Open() and Close() databases frequently.

我不知道应该连接多长时间。现在,我会在必要时打开每个 http 请求的连接。是不是太频繁了?

最佳答案

在同一份文件的下方,它写道:

Instead, create one sql.DB object for each distinct datastore you need to access, and keep it until the program is done accessing that datastore. Pass it around as needed, or make it available somehow globally, but keep it open. And don’t Open() and Close() from a short-lived function. Instead, pass the sql.DB into that short-lived function as an argument.

If you don’t treat the sql.DB as a long-lived object, you could experience problems such as poor reuse and sharing of connections, running out of available network resources, or sporadic failures due to a lot of TCP connections remaining in TIME_WAIT status. Such problems are signs that you’re not using database/sql as it was designed.

打开和关闭数据库连接是一项代价高昂的操作,因此您希望尽可能避免这种情况。您肯定不想在每次请求后关闭连接(除非一天只有几天,即使这样您也可以在应用程序运行时保持连接打开状态)

database/sql 包使用connection pooling在引擎盖下,因此您不必担心管理多个连接。

关于mysql - 一个mysql连接应该在golang中存活多长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29558653/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com