perf: 提升后端高并发承载能力
This commit is contained in:
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
@@ -37,15 +38,32 @@ func InitDB() {
|
||||
log.Fatalf("Failed to connect database: %v", err)
|
||||
}
|
||||
|
||||
// Configure connection pool settings
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to get database instance: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(10)
|
||||
sqlDB.SetMaxIdleConns(5)
|
||||
maxOpen := runtime.NumCPU()*2 + 1
|
||||
if maxOpen < 4 {
|
||||
maxOpen = 4
|
||||
}
|
||||
if maxOpen > 32 {
|
||||
maxOpen = 32
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(maxOpen)
|
||||
sqlDB.SetMaxIdleConns(maxOpen)
|
||||
sqlDB.SetConnMaxIdleTime(10 * time.Minute)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
for _, pragma := range []string{
|
||||
"PRAGMA synchronous=NORMAL",
|
||||
"PRAGMA temp_store=MEMORY",
|
||||
"PRAGMA foreign_keys=ON",
|
||||
} {
|
||||
if execErr := DB.Exec(pragma).Error; execErr != nil {
|
||||
log.Fatalf("Failed to apply %s: %v", pragma, execErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-migrate the schema
|
||||
err = DB.AutoMigrate(&model.User{}, &model.Room{})
|
||||
if err != nil {
|
||||
@@ -57,7 +75,7 @@ func InitDB() {
|
||||
|
||||
ensureAdminUser()
|
||||
|
||||
monitor.Infof("Database initialized successfully with WAL mode and connection pooling")
|
||||
monitor.Infof("Database initialized successfully with WAL mode and tuned SQLite pragmas")
|
||||
}
|
||||
|
||||
func ensureAdminUser() {
|
||||
@@ -77,14 +95,17 @@ func ensureAdminUser() {
|
||||
updates := map[string]interface{}{}
|
||||
if user.Role != "admin" {
|
||||
updates["role"] = "admin"
|
||||
user.Role = "admin"
|
||||
}
|
||||
if !user.Enabled {
|
||||
updates["enabled"] = true
|
||||
user.Enabled = true
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
DB.Model(&user).Updates(updates)
|
||||
monitor.Warnf("Admin account normalized for username=%s", adminUsername)
|
||||
}
|
||||
cacheUser(user)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -115,5 +136,10 @@ func ensureAdminUser() {
|
||||
monitor.Warnf("Failed to create default admin room: %v", roomErr)
|
||||
}
|
||||
|
||||
cacheUser(newAdmin)
|
||||
if room.ID != 0 {
|
||||
cacheRoom(room)
|
||||
}
|
||||
|
||||
monitor.Warnf("Default admin created for username=%s; change the password after first login", adminUsername)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user