update
This commit is contained in:
58
cmd/root.go
58
cmd/root.go
@ -4,20 +4,17 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"my-spiders/internal/config"
|
||||
"my-spiders/internal/ingest"
|
||||
)
|
||||
|
||||
var (
|
||||
DB *gorm.DB
|
||||
cfgFile string
|
||||
debug bool // 命令行 debug 标志
|
||||
IngestClient *ingest.Client // 入库管线客户端(enabled 时非 nil)
|
||||
cfgFile string
|
||||
debug bool // 命令行 debug 标志
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "spider-cli",
|
||||
@ -39,10 +36,10 @@ func init() {
|
||||
// 新增全局 -d / --debug 参数
|
||||
rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "d", false, "调试模式 (仅输出不入库)")
|
||||
|
||||
cobra.OnInitialize(initConfigAndDB)
|
||||
cobra.OnInitialize(initConfig)
|
||||
}
|
||||
|
||||
func initConfigAndDB() {
|
||||
func initConfig() {
|
||||
// 1. 初始化配置文件
|
||||
if err := config.InitConfig(cfgFile); err != nil {
|
||||
log.Fatalf("[致命错误] %v", err)
|
||||
@ -53,39 +50,14 @@ func initConfigAndDB() {
|
||||
config.GlobalConfig.App.Debug = true
|
||||
}
|
||||
|
||||
isDebug := config.GlobalConfig.App.Debug
|
||||
|
||||
// 2. 初始化数据库连接
|
||||
dbCfg := config.GlobalConfig.Database
|
||||
var err error
|
||||
DB, err = gorm.Open(mysql.Open(dbCfg.DSN), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Warn),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if isDebug {
|
||||
log.Println("[Warning] 数据库连接失败,当前处于 Debug 模式,将跳过数据库操作...")
|
||||
DB = nil
|
||||
return
|
||||
}
|
||||
log.Fatalf("[致命错误] 数据库连接失败: %v", err)
|
||||
// 2. 入库管线:enabled 时构建 HMAC 上报客户端,并用后台盐值初始化 hashid 编码。
|
||||
// spider 不再直连数据库,所有落库经后端 ingest 接口完成。
|
||||
ic := config.GlobalConfig.Ingest
|
||||
if ic.Enabled && ic.Endpoint != "" {
|
||||
ingest.InitHashID(ic.HashIDSecret)
|
||||
IngestClient = ingest.NewClient(ic.Endpoint, ic.Secret)
|
||||
log.Printf("[Info] 入库管线已启用 -> %s", ic.Endpoint)
|
||||
} else {
|
||||
IngestClient = nil
|
||||
}
|
||||
|
||||
// 3. 设置连接池参数
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil || sqlDB.Ping() != nil {
|
||||
if isDebug {
|
||||
log.Println("[Warning] 数据库 Ping 失败,当前处于 Debug 模式,将跳过数据库操作...")
|
||||
DB = nil
|
||||
return
|
||||
}
|
||||
log.Fatalf("[致命错误] 数据库不可用: %v", err)
|
||||
}
|
||||
|
||||
sqlDB.SetMaxOpenConns(dbCfg.MaxOpenConns)
|
||||
sqlDB.SetMaxIdleConns(dbCfg.MaxIdleConns)
|
||||
sqlDB.SetConnMaxLifetime(time.Duration(dbCfg.ConnMaxLifetime) * time.Minute)
|
||||
sqlDB.SetConnMaxIdleTime(time.Duration(dbCfg.ConnMaxIdleTime) * time.Minute)
|
||||
|
||||
log.Printf("[Info] MySQL 连接池初始化完成 | MaxOpen: %d | MaxIdle: %d", dbCfg.MaxOpenConns, dbCfg.MaxIdleConns)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user