完善数据库 SQL 约束与运维治理

This commit is contained in:
yml2213
2026-08-31 12:58:28 +08:00
parent 1ee7d17712
commit ad279049a0
12 changed files with 283 additions and 8 deletions
+25
View File
@@ -5,6 +5,7 @@ import (
"os"
"strconv"
"strings"
"time"
)
type Config struct {
@@ -29,6 +30,7 @@ type Config struct {
Realname RealnameConfig
Log LogConfig
RateLimit RateLimitConfig
Database DatabaseConfig
BackupStatusFile string
}
@@ -70,6 +72,14 @@ type RateLimitConfig struct {
RequestsPerMinute int
}
type DatabaseConfig struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
ConnMaxIdleTime time.Duration
SlowQueryThreshold time.Duration
}
func Load() Config {
return Config{
AppEnv: getEnv("APP_ENV", "development"),
@@ -131,6 +141,13 @@ func Load() Config {
Enabled: getEnvBool("RATE_LIMIT_ENABLED", true),
RequestsPerMinute: getEnvInt("RATE_LIMIT_REQUESTS_PER_MINUTE", 300),
},
Database: DatabaseConfig{
MaxOpenConns: getEnvIntMin("DATABASE_MAX_OPEN_CONNS", 50, 1),
MaxIdleConns: getEnvIntMin("DATABASE_MAX_IDLE_CONNS", 10, 0),
ConnMaxLifetime: time.Duration(getEnvIntMin("DATABASE_CONN_MAX_LIFETIME_MINUTES", 30, 1)) * time.Minute,
ConnMaxIdleTime: time.Duration(getEnvIntMin("DATABASE_CONN_MAX_IDLE_TIME_MINUTES", 5, 0)) * time.Minute,
SlowQueryThreshold: time.Duration(getEnvIntMin("DATABASE_SLOW_QUERY_THRESHOLD_MS", 500, 1)) * time.Millisecond,
},
BackupStatusFile: getEnv("BACKUP_STATUS_FILE", "/var/run/hfb-backup-status/status.json"),
}
}
@@ -208,6 +225,14 @@ func getEnvInt(key string, fallback int) int {
return parsed
}
func getEnvIntMin(key string, fallback, minimum int) int {
value := getEnvInt(key, fallback)
if value < minimum {
return fallback
}
return value
}
func getEnvBool(key string, fallback bool) bool {
value := os.Getenv(key)
if value == "" {