数据库连接限制是否应等于连接的进程数?

数据库连接限制是否应等于连接的进程数?

我注意到 PostgreSQL 和 MySQL 默认有 100 个客户端连接限制。我想知道我是否应该关闭这个限制,因为 Web 服务器在同一个盒子上,而且我只需要连接大约 20 个 PHP 进程。

此设置是否应该匹配或者超过尝试连接的进程数?

答案1

在 PostgreSQL(我不知道 MySQL)中有最大连接数属性定义为:

确定数据库服务器的最大并发连接数。默认值通常为 100 个连接,但如果您的内核设置不支持(在 initdb 期间确定),则可能会更少。此参数只能在服务器启动时设置。

增加此参数可能会导致 PostgreSQL 请求比操作系统默认配置允许的更多的 System V 共享内存或信号量。请参阅第 17.4.1 节以获取有关如何调整这些参数的信息(如有必要)。

客户端连接的有效限制定义为:

max_connections - superuser_reserved_connections

默认值为超级用户保留连接是 3。

您需要采取一些透视视角。今天假设 40 max_connections 对您来说是安全的,并且它可以保持一些 OS 资源可用(信号量和共享内存,如文档),但明天可能还不够:

psql: FATAL:  sorry, too many clients already

让我们计算一下您获得的利润:

minSemaphoresSets = ceil((max_connections + autovacuum_max_workers)/16)

默认值为autovacuum_max_workers为 3,因此:

prevSets = ceil((100 + 3)/16) = 7
newSets = ceil((40 + 3)/16) = 3

每个(Postgres)集合始终具有 17 个信号量,因此您有 68 个信号量是安全的:

ipcs -s | grep postgres
0x0052e2c1 589824     postgres  600        17        
0x0052e2c2 622593     postgres  600        17        
0x0052e2c3 655362     postgres  600        17        
0x0052e2c4 688131     postgres  600        17        
0x0052e2c5 720900     postgres  600        17        
0x0052e2c6 753669     postgres  600        17        
0x0052e2c7 786438     postgres  600        17
# changing max_connections from 100 to 40
pg_ctlcluster 8.3 main restart
ipcs -s | grep postgres
0x0052e2c1 819200     postgres  600        17        
0x0052e2c2 851969     postgres  600        17        
0x0052e2c3 884738     postgres  600        17

对于共享内存,它大约是 1 MiB(看看表 17-2更多细节):

ipcs -m | grep postgres
0x0052e2c1 0          postgres  600        29368320   4
# changing max_connections from 100 to 40
pg_ctlcluster 8.3 main restart
ipcs -m | grep postgres
0x0052e2c1 425984     postgres  600        28270592   4

如您所见,这并不是太多,因此,如果您不需要这样的优化,则可以使用默认限制。

相关内容