An article explaining in detail how to configure high-performance sql.DB in Go

藏色散人
Release: 2022-01-27 16:44:19
forward
2977 people have browsed it

This article is provided by the golang tutorial column to introduce how Go configures high-performance sql.DB. I hope it will be helpful to friends in need! There are many tutorials on Go's

sql.DB

type and how to use it to perform SQL database queries. But most of it doesn't cover the SetMaxOpenConns(), SetMaxIdleConns() and SetConnMaxLifetime() methods, which you can use to configure sql.DB 's behavior and change its performance. In this article I will explain in detail what these settings do and explain the (positive and negative) effects they can have.

Open and idle connections

A sql.DB object is a database connection pool, which contains "in use" and "idle" connections. An active connection means that you are using it to perform database tasks, such as executing SQL statements or row queries. When the task is completed the connection is free.
When you create sql.DB to perform database tasks, it will first check whether there are available idle connections in the connection pool. If there is a connection available, then Go will reuse the existing connection and mark it as in use during the execution of the task. If there is no free connection in the pool and you need one, Go will create a new one.

SetMaxOpenConns method

By default, the number of open connections at the same time is unlimited (including idle). But you can implement custom limits through the

SetMaxOpenConns()

method as follows:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 初始化一个新的连接池 db, err := sql.Open(&quot;postgres&quot;, &quot;postgres://user:pass@localhost/db&quot;) if err != nil { log.Fatal(err) } // 设置当前最大开放连接数(包括空闲和正在使用的)为5。 // 如果设置为0代表连接数没有限制,默认是没有限制数量的。 db.SetMaxOpenConns(5)</pre><div class="contentsignin">Copy after login</div></div>In this example code, the connection pool now has 5 concurrent open connections. If all 5 connections are already marked as in use and another new connection is required, the application will be forced to wait until one of the 5 connections is released and becomes free.

To illustrate the impact of changing

MaxOpenConns

, I ran a benchmark with the maximum number of open connections set to 1, 2, 5, 10, and unlimited. The benchmark executes parallel INSERT statements on a PostgreSQL database, you can find the code here. Test results:

BenchmarkMaxOpenConns1-8 500 3129633 ns/op 478 B/op 10 allocs/op
BenchmarkMaxOpenConns2-8 100 0 2181641 ns/op 470 B/op 10 allocs/op

BenchmarkMaxOpenConns5-8 2000 859654 ns/op 493 B/op 10 allocs/op
BenchmarkMaxOpenConns10-8 2000 5453 94 ns/op 510 B/op 10 allocs/op
BenchmarkMaxOpenConnsUnlimited-8 2000 531030 ns/op 479 B/op 9 allocs/op
PASS

For this benchmark, we can see that the more connections we are allowed to open, the more time it takes to perform an
INSERT

operation on the database The less (when the number of open connections is 1, the execution speed is 3129633ns/op, while for unlimited connections: 531030ns/op - about 6 times faster). This is because the more connections you allow to open, the more database queries that can be executed concurrently.

SetMaxIdleConns method

By default, sql.DB allows up to 2 idle connections to be retained in the connection pool. You can change it via the SetMaxIdleConns()
method, as shown below: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 初始化一个新的连接池 db, err := sql.Open(&quot;postgres&quot;, &quot;postgres://user:pass@localhost/db&quot;) if err != nil { log.Fatal(err) } // 设置最大空闲连接数为5。 将此值设置为小于或等于0将意味着不保留空闲连接。 db.SetMaxIdleConns(5)</pre><div class="contentsignin">Copy after login</div></div> In theory, allowing more idle connections in the pool will improve performance, because then there will be less New connections may be established from scratch - thus helping to improve database performance.

Let’s look at the same benchmark with max idle connections set to none, 1, 2, 5 and 10:

BenchmarkMaxIdleConnsNone-8         300     4567245 ns/op     58174 B /op 625 allocs/op
BenchmarkMaxIdleConns1-8 2000 568765 ns/op 2596 B/op 32 allocs/op

BenchmarkMaxIdleConns2-8 2 000 529359 ns/op 596 B/op 11 allocs/op
BenchmarkMaxIdleConns5-8 2000 506207 ns/op 451 B/op 9 allocs/op
BenchmarkMaxIdleConns10-8 2000 501639 ns/op 450 B/op 9 allocs/op
PASS

MaxIdleConns设置为none时,必须为每个INSERT从头创建一个新的连接,我们可以从基准测试中看到,平均运行时和内存使用量相对较高。

只允许保留和重用一个空闲连接对基准测试影响特别明显——它将平均运行时间减少了大约8倍,内存使用量减少了大约20倍。继续增加空闲连接池的大小会使性能变得更好,尽管改进并不明显。

那么,您应该维护一个大的空闲连接池吗?答案取决于应用程序。重要的是要意识到保持空闲连接是有代价的—它占用了可以用于应用程序和数据库的内存。

还有一种可能是,如果一个连接空闲时间太长,那么它可能会变得不可用。例如,MySQL的wait_timeout设置将自动关闭任何8小时(默认)内未使用的连接。

当发生这种情况时,sql.DB会优雅地处理它。坏连接将自动重试两次,然后放弃,此时Go将该连接从连接池中删除,并创建一个新的连接。因此,将MaxIdleConns设置得太大可能会导致连接变得不可用,与空闲连接池更小(使用更频繁的连接更少)相比,会占有更多的资源。所以,如果你很可能很快就会再次使用,你只需保持一个空闲的连接。

最后要指出的是,MaxIdleConns应该总是小于或等于MaxOpenConns.
。Go强制执行此操作,并在必要时自动减少MaxIdleConns

SetConnMaxLifetime方法
现在让我们看看SetConnMaxLifetime()方法,它设置连接可重用的最大时间长度。如果您的SQL数据库也实现了最大连接生命周期,或者—例如—您希望方便地在负载均衡器后交换数据库,那么这将非常有用。
你可以这样使用它:

// 初始化一个新的连接池
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
if err != nil {
    log.Fatal(err)
}

// 将连接的最大生存期设置为1小时。将其设置为0意味着没有最大生存期,连接将永远可重用(这是默认行为)
db.SetConnMaxLifetime(time.Hour)
Copy after login

在这个例子中,所有的连接都将在创建后1小时“过期”,并且在过期后无法重用。但注意:

  • 这并不能保证连接将在池中存在整整一个小时;很有可能,由于某些原因,连接变得不可用,并在此之前自动关闭。
  • 一个连接在创建后一个多小时仍然可以被使用——它只是在这个时间之后不能被重用。
  • 这不是空闲超时。连接将在第一次创建后1小时过期——而不是在最后一次空闲后1小时。
  • 每隔一秒自动运行一次清理操作,从连接池中删除“过期”的连接。

从理论上讲,ConnMaxLifetime越短,连接过期的频率就越高——因此,需要从头创建连接的频率就越高。为了说明这一点,我运行了将ConnMaxLifetime设置为100ms、200ms、500ms、1000ms和无限(永远重用)的基准测试,默认设置为无限打开连接和2个空闲连接。

这些时间段显然比您在大多数应用程序中使用的时间要短得多,但它们有助于很好地说明行为。

BenchmarkConnMaxLifetime100-8 2000 637902 ns/op 2770 B/op 34 allocs/op
BenchmarkConnMaxLifetime200-8 2000 576053 ns/op 1612 B/op 21 allocs/op
BenchmarkConnMaxLifetime500-8 2000 558297 ns/op 913 B/op 14 allocs/op
BenchmarkConnMaxLifetime1000-8 2000 543601 ns/op 740 B/op 12 allocs/op
BenchmarkConnMaxLifetimeUnlimited-8 3000 532789 ns/op 412 B/op 9 allocs/op
PASS

在这些特定的基准测试中,我们可以看到,与无限生存期相比,在100ms生存期时内存使用量增加了3倍以上,而且每个INSERT的平均运行时也稍微长一些。

如果您在代码中设置了ConnMaxLifetime,那么一定要记住连接将过期(随后重新创建)的频率。例如,如果您总共有100个连接,而ConnMaxLifetime为1分钟,那么您的应用程序可能每秒钟杀死和重新创建1.67个连接(平均值)。您不希望这个频率太大,最终会阻碍性能,而不是提高性能。

连接数量超出
最后,如果不说明超过数据库连接数量的硬限制将会发生什么,那么本文就不完整了。 为了说明这一点,我将修改postgresql.conf文件,这样总共只允许5个连接(默认是100个)…

max_connections = 5
Copy after login

然后在无限连接的情况下重新运行基准测试……

BenchmarkMaxOpenConnsUnlimited-8 — FAIL: BenchmarkMaxOpenConnsUnlimited-8
main_test.go: 14: pq: sorry, too many clients already
main_test.go: 14: pq: sorry, too many clients already
main_test.go: 14: pq: sorry, too many clients already
FAIL

一旦达到5个连接的硬限制,数据库驱动程序(pq)立即返回一个太多客户端连接的错误消息,而无法完成INSERT。为了防止这个错误,我们需要将sql.DB中打开连接的最大总数(正在使用的+空闲的)设置为低于5。像这样:

// 初始化一个新的连接池
db, err := sql.Open("postgres", "postgres://user:pass@localhost/db")
if err != nil {
    log.Fatal(err)}
    // 将打开的连接数(正在使用的连接+空闲的连接)设置为最大总数3。
 db.SetMaxOpenConns (3)
Copy after login

现在,sql.DB在任何时候最多只能创建3个连接,基准测试运行时应该不会出现任何错误。但是这样做需要注意:当达到开放连接数限制,并且所有连接都在使用时,应用程序需要执行的任何新的数据库任务都将被迫等待,直到连接标记为空闲。例如,在web应用程序的上下文中,用户的HTTP请求看起来会“挂起”,甚至在等待数据库任务运行时可能会超时。

为了减轻这种情况,你应该始终在一个上下文中传递。在调用数据库时,启用上下文的方法(如ExecContext()),使用固定的、快速的超时上下文对象。


总结
1、根据经验,应该显式设置MaxOpenConns值。这应该小于数据库和基础设施对连接数量的硬性限制。
2、一般来说,更高的MaxOpenConnsMaxIdleConns值将带来更好的性能。但你应该注意到效果是递减的,连接池空闲连接太多(连接没有被重用,最终会变坏)实际上会导致性能下降。
3、为了降低上面第2点带来的风险,您可能需要设置一个相对较短的ConnMaxLifetime。但你也不希望它太短,导致连接被杀死或不必要地频繁重建。
4、MaxIdleConns应该总是小于或等于MaxOpenConns
对于中小型web应用程序,我通常使用以下设置作为起点,然后根据实际吞吐量水平的负载测试结果进行优化。

db.SetMaxOpenConns(25)db.SetMaxIdleConns(25)db.SetConnMaxLifetime(5*time.Minute)
Copy after login

到此这篇关于golang配制高性能sql.DB的使用的文章就介绍到这了                                                     

The above is the detailed content of An article explaining in detail how to configure high-performance sql.DB in Go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!