diff --git a/internal/dao/mysql/mysql.go b/internal/dao/mysql/mysql.go index 8b7f94c..834b5d1 100644 --- a/internal/dao/mysql/mysql.go +++ b/internal/dao/mysql/mysql.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "sync" + "time" "go.uber.org/zap" "gorm.io/driver/mysql" @@ -24,19 +25,27 @@ var ( ) // 使用单例模式防止重复创建 -func New(cfg *config.Config, logger *zap.Logger) *gorm.DB { +func New(cfg *config.Config, lg *zap.Logger) *gorm.DB { once.Do(func() { dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", cfg.Mysql.User, cfg.Mysql.Password, cfg.Mysql.Host, cfg.Mysql.Port, cfg.Mysql.Database) var err error mysqlconfig := mysql.Config{ DSN: dsn, } - logger := zapgorm2.New(logger) + logger := zapgorm2.New(lg) logger.SetAsDefault() - db, err = gorm.Open(mysql.New(mysqlconfig), &gorm.Config{Logger: logger}) + for i := 0; i < 3; i++ { + db, err = gorm.Open(mysql.New(mysqlconfig), &gorm.Config{Logger: logger}) + if err == nil { + break + } + lg.Error("connect to mysql failed", zap.Error(err), zap.Int("retry", i)) + time.Sleep(time.Second * 3) + } if err != nil { panic(ErrCouldNotConnect) } + lg.Info("connect to mysql success") if err = db.AutoMigrate(&model.User{}, &model.Video{}, &model.Comment{}); err != nil { panic(err) } diff --git a/internal/dao/redis/redis.go b/internal/dao/redis/redis.go index 56e5358..5aee5c5 100644 --- a/internal/dao/redis/redis.go +++ b/internal/dao/redis/redis.go @@ -4,6 +4,7 @@ import ( "context" "strings" "sync" + "time" "github.com/go-redis/redis/v8" "github.com/yunyandz/tiktok-demo-backend/internal/config" @@ -28,9 +29,18 @@ func New(cfg *config.Config, logger *zap.Logger) *redis.Client { Password: cfg.Redis.Password, DB: cfg.Redis.Database, }) - if _, err := rdb.Ping(context.TODO()).Result(); err != nil { + var err error + for i := 0; i < 3; i++ { + if _, err = rdb.Ping(context.TODO()).Result(); err == nil { + break + } + logger.Error("connect to redis failed", zap.Error(err), zap.Int("retry", i)) + time.Sleep(time.Second * 3) + } + if err != nil { panic(err) } + logger.Info("connect to redis success") logger.Sugar().Infof("redis connect success, host: %s, database: %d", host, cfg.Redis.Database) }) return rdb