我真的需要 Postgres 中的空闲连接吗?

Sat*_*atz 3 database postgresql pgbouncer postgresql-9.1 spring-boot

我在 Spring Boot (1.5.1.RELEASE) 中有一个使用 Postgres DB (9.1-901-1) 的项目。

当我在生产中运行这个应用程序时,它会在数据库中创建多达 100 个空闲连接。

所以我覆盖了默认配置来控制创建“N”个空闲连接。请检查以下配置:

datasource:
  driverClassName: org.postgresql.Driver
  url: jdbc:postgresql://localhost:5432/db_name
  username: root
  password: root
  tomcat:
  # default value is 100 but postgres' default is 100 as well. To prevent "PSQLException: FATAL: sorry, too many
  # clients already", we decrease the max-active value here. Which should be sufficient, by the way
    max-active: 10
    max-idle: 10
    min-idle: 5
    max-wait: 30000
    time-between-eviction-runs-millis: 5000
    min-evictable-idle-time-millis: 60000
    jmx-enabled: true
Run Code Online (Sandbox Code Playgroud)

现在它创建了 5 个与 DB 的空闲连接。

我正在通过执行以下查询来验证这一点。

select * from pg_stat_activity;
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,我真的需要 5 个用于生产环境的空闲连接。

如果我像下面这样更改我的配置会发生什么?这会正常工作吗?

 max-active: 1
 max-idle: 1
 min-idle: 0
Run Code Online (Sandbox Code Playgroud)

还想知道 PgBouncer 将如何帮助解决这种情况?是否有必要为 Postgres 安装 PgBouncer?

Moh*_*tha 5

你提出的配置是绝对不推荐的。一个完整的DB连接周期会经历

  1. 建立 TCP 连接
  2. 验证凭据
  3. 连接就绪
  4. 执行命令
  5. 断开

通过维护与数据库的空闲连接(连接池),您可以节省步骤 1-3 所花费的时间,从而获得更好的性能。

您应该根据将连接的微服务的最大实例数调整数据库上的设置。例如,如果微服务实例的最大数量为 5,并且该服务配置为维护 50 个空闲连接,那么请确保您的数据库配置为满足至少 250 个连接。

要获得微服务的最小连接设置,您需要根据您的非功能需求和服务负载测试进行一些测试。