数据库连接限制应该等于连接的进程数吗?

Xeo*_*oss 5 mysql postgresql database connection

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

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

Grz*_*ski 4

在 PostgreSQL(我不知道 MySQL)中,max_connections属性定义为:

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

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

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

max_connections - superuser_reserved_connections
Run Code Online (Sandbox Code Playgroud)

superuser_reserved_connections的默认值为3。

你需要采取一些观点。今天,假设 40 个 max_connections 对您来说是安全的,并且它可以保留一些操作系统资源(如文档中所述的信号量和共享内存),但明天它可能还不够:

psql: FATAL:  sorry, too many clients already
Run Code Online (Sandbox Code Playgroud)

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

minSemaphoresSets = ceil((max_connections + autovacuum_max_workers)/16)
Run Code Online (Sandbox Code Playgroud)

autovacuum_max_workers的默认值为3,因此:

prevSets = ceil((100 + 3)/16) = 7
newSets = ceil((40 + 3)/16) = 3
Run Code Online (Sandbox Code Playgroud)

每个 (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
Run Code Online (Sandbox Code Playgroud)

对于共享内存,约为 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
Run Code Online (Sandbox Code Playgroud)

如您所见,它并不算太多,因此如果您不需要此类优化,可以使用默认限制。