Skip to content

Commit

Permalink
Merge pull request #52 from sunmi-OS/batter_new_gorm
Browse files Browse the repository at this point in the history
优化 grom 的初始化
  • Loading branch information
wenzhenxi authored Sep 8, 2020
2 parents 20dfd2d + 051db96 commit 86407fd
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 4 deletions.
15 changes: 11 additions & 4 deletions gorm/gorm.go
Original file line number Diff line number Diff line change
@@ -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 (
Expand Down Expand Up @@ -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)
Expand Down
21 changes: 21 additions & 0 deletions retry/retry.go
Original file line number Diff line number Diff line change
@@ -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
}
25 changes: 25 additions & 0 deletions retry/retry_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 86407fd

Please sign in to comment.