Skip to content

Commit

Permalink
fix: 加入数据库连接重试
Browse files Browse the repository at this point in the history
  • Loading branch information
YuuinIH committed Jun 12, 2022
1 parent 471ffef commit a43c0d5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
15 changes: 12 additions & 3 deletions internal/dao/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"sync"
"time"

"go.uber.org/zap"
"gorm.io/driver/mysql"
Expand All @@ -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)
}
Expand Down
12 changes: 11 additions & 1 deletion internal/dao/redis/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"strings"
"sync"
"time"

"github.com/go-redis/redis/v8"
"github.com/yunyandz/tiktok-demo-backend/internal/config"
Expand All @@ -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
Expand Down

0 comments on commit a43c0d5

Please sign in to comment.