diff --git a/gorm/gorm.go b/gorm/gorm.go index 09a0ad5..85872e2 100644 --- a/gorm/gorm.go +++ b/gorm/gorm.go @@ -1,14 +1,15 @@ package gorm import ( - "fmt" "sync" "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" + "github.com/sunmi-OS/gocore/retry" "github.com/sunmi-OS/gocore/viper" + "github.com/sunmi-OS/gocore/xlog" ) var ( @@ -36,10 +37,16 @@ func NewDB(dbname string) { err error ) - for orm, err = openORM(dbname); err != nil; { - fmt.Println("Database connection exception! 5 seconds to retry") - time.Sleep(5 * time.Second) + err = retry.Retry(func() error { orm, err = openORM(dbname) + if err != nil { + xlog.Errorf("NewDB(%s) error:%+v", dbname, err) + return err + } + return nil + }, 5, 3*time.Second) + if err != nil || orm == nil { + panic(err) } Gorm.Store(dbname, orm) diff --git a/retry/retry.go b/retry/retry.go new file mode 100644 index 0000000..acd53ac --- /dev/null +++ b/retry/retry.go @@ -0,0 +1,21 @@ +package retry + +import ( + "time" + + "github.com/sunmi-OS/gocore/xlog" +) + +// Retry 重试 func 最大次数,间隔 +func Retry(callback func() error, maxRetries int, interval time.Duration) error { + var err error + for i := 1; i <= maxRetries; i++ { + if err = callback(); err != nil { + xlog.Warnf("Retry(%d) error(%+v)", i, err) + time.Sleep(interval) + continue + } + return nil + } + return err +} diff --git a/retry/retry_test.go b/retry/retry_test.go new file mode 100644 index 0000000..f2ed49a --- /dev/null +++ b/retry/retry_test.go @@ -0,0 +1,25 @@ +package retry + +import ( + "fmt" + "sync/atomic" + "testing" + "time" + + "github.com/sunmi-OS/gocore/xlog" +) + +func TestRetry(t *testing.T) { + var count int32 = 0 + + err := Retry(func() error { + if count < 3 { + atomic.AddInt32(&count, 1) + return fmt.Errorf("%d count retry finished", count) + } + return nil + }, 5, 2*time.Second) + if err != nil { + xlog.Error(err) + } +}