Created
December 31, 2020 02:58
-
-
Save weihanchen/fb29a0cae00d8e6af12a223441ba3cac to your computer and use it in GitHub Desktop.
Go Retry Policy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func retry(maxRetryCount int, retryPeriod int, job func() error) error { | |
for retryCount := 1; ; retryCount++ { | |
err := job() | |
if err == nil { | |
return nil | |
} | |
// 進入retry模式 | |
if retryCount <= maxRetryCount { | |
glog.Errorf("error: %s, retry: %d, max: %d, wait: %ds", err, retryCount, maxRetryCount, retryPeriod) | |
time.Sleep(time.Second * time.Duration(retryPeriod)) | |
} else { | |
return err | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func Update(id string, update bson.M, timeout time.Duration, opts ...*options.FindOneAndUpdateOptions) (*mongo.SingleResult, error) { | |
var result *mongo.SingleResult | |
if err := b.retry(func() error { | |
objID, err := primitive.ObjectIDFromHex(id) | |
if err != nil { | |
return err | |
} | |
filter := bson.M{ | |
"_id": objID, | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), timeout) | |
defer cancel() | |
returnDocument := options.After | |
defaultOpts := &options.FindOneAndUpdateOptions{ | |
ReturnDocument: &returnDocument, | |
} | |
opts = append(opts, defaultOpts) | |
result = b.Collection.FindOneAndUpdate(ctx, filter, update, opts...) | |
if err := result.Err(); err != nil { | |
return err | |
} | |
return nil | |
}); err != nil { | |
glog.Fatal("retry失敗, 請進行後續處理") | |
} | |
return result, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment