chore(retry): add retry from utils

This commit is contained in:
Medzik 2021-09-05 10:50:41 +00:00
parent c8091847d0
commit b3decb1561
6 changed files with 41 additions and 39 deletions

View file

@ -9,20 +9,23 @@ import (
var cacheURL []string
func cache(retry int) {
func cache() {
cacheURL = cacheURL[:0]
results, err := mongo.GetAll()
if common.CheckErr(err, "get documents from db") {
if retry == 5 {
time.Sleep(500 * time.Millisecond)
cache(retry + 1)
} else {
return
err := common.Retry(1, 1*time.Second, func() error {
results, err := mongo.GetAll()
if err != nil {
return err
}
}
for _, value := range results {
cacheURL = append(cacheURL, value.URL)
for _, value := range results {
cacheURL = append(cacheURL, value.URL)
}
return nil
})
if err != nil {
log.Error(err)
}
}

View file

@ -13,7 +13,7 @@ var cacheRetry int
func ping() int {
if cacheRetry >= config.Toml.Backend.Cache {
cache(0)
cache()
cacheRetry = 0
}
cacheRetry++

View file

@ -11,7 +11,7 @@ import (
var log = common.Log
func StopAfterPing() {
cache(0)
cache()
num := ping()
// timeout

View file

@ -8,7 +8,7 @@ import (
func Ticker() {
// On Start
cache(0)
cache()
ping()
ticker := time.NewTicker(config.Toml.Backend.Ping * time.Minute)

View file

@ -2,7 +2,6 @@ package mongo
import (
"context"
"os"
"time"
"github.com/MedzikUser/go-utils/common"
@ -15,33 +14,27 @@ import (
var Client mongo.Client
var Coll *mongo.Collection
func Connect(retry ...int8) {
if len(retry) == 0 {
retry = append(retry, 0)
}
func Connect() error {
return common.Retry(5, 2*time.Second, func() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if retry[0] == 5 {
os.Exit(1)
}
Client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Mongo_URI))
if common.CheckErr(err, "connect to db") {
time.Sleep(2 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return err
}
Client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.Mongo_URI))
if common.CheckErr(err, "connect to db") {
time.Sleep(2 * time.Second)
Connect(retry[0] + 1)
err = Client.Ping(ctx, readpref.Primary())
if common.CheckErr(err, "ping db") {
time.Sleep(2 * time.Second)
return
}
return err
}
err = Client.Ping(ctx, readpref.Primary())
if common.CheckErr(err, "ping db") {
time.Sleep(2 * time.Second)
Connect(retry[0] + 1)
Coll = Client.Database(config.Mongo_DB).Collection(config.Mongo_Collection)
return
}
Coll = Client.Database(config.Mongo_DB).Collection(config.Mongo_Collection)
return nil
})
}

View file

@ -87,7 +87,13 @@ func main() {
}
}
mongo.Connect()
err := mongo.Connect()
if err != nil {
log.Error(err)
os.Exit(1)
}
if config.Toml.AutoUpdate.Enabled {
wg.Add(1)