feat(db): implement read-write splitting for postgres
All checks were successful
Build Backend / build (push) Successful in 2m1s
Build Backend / build-docker (push) Successful in 1m26s

Add support for database read replicas using the GORM dbresolver plugin. This allows for scaling read operations by distributing them across one or multiple replica nodes.

- Update `DatabaseConfig` to support single and multiple replica configurations.
- Add configuration options for replica connection pooling and selection policy.
- Integrate `dbresolver` in the database initialization process for PostgreSQL.
- Add helper methods to aggregate replica configurations.
This commit is contained in:
2026-05-15 14:44:40 +08:00
parent de0766df5e
commit f63c795dcb
4 changed files with 90 additions and 10 deletions

View File

@@ -21,6 +21,28 @@ database:
password: postgres
dbname: with_you
sslmode: disable
# 读写分离配置(仅 postgres 模式生效,不配置则所有请求走主库)
# 单副本配置(支持环境变量):
# APP_DATABASE_REPLICA_HOST, APP_DATABASE_REPLICA_PORT, APP_DATABASE_REPLICA_USER,
# APP_DATABASE_REPLICA_PASSWORD, APP_DATABASE_REPLICA_DBNAME, APP_DATABASE_REPLICA_SSLMODE
# replica:
# host: replica1.internal
# port: 5432
# user: readonly
# password: readonly_pass
# dbname: with_you
# sslmode: disable
# 多副本配置(仅 YAML环境变量不支持切片结构体:
# replicas:
# - host: replica1.internal
# port: 5432
# user: readonly
# password: readonly_pass
# dbname: with_you
# sslmode: disable
# replica_policy: random # random
# replica_max_idle_conns: 10
# replica_max_open_conns: 100
max_idle_conns: 10
max_open_conns: 100
log_level: warn