Scene
Services rely on third-party services or other services, but sometimes third-party services have occasional problems and will be quickly restored, and our system may have problems due to these occasional problems.
Therefore, the reliability of the service since then cannot be guaranteed, but we can ensure that our service is stable and reliable through other methods.
The retry mechanism can help us build robust services. For example, when calling a third-party service or performing an operation, the execution fails. We can ask it to try again a few times before throwing an error.
Design Principles
Retry mechanism: A method or function fails to execute and re-executes. After trying to execute again, the attempt ends after several failures. Success once during the period means success.
- Number of retry times
- Need to be re-executed
func add() (string, error) { var i = 1 var j = 2 result := i + j return (result), nil } func RetryFunc(count int, cback func() (string, error)) { for i := 0; i < count; i++ { result, err := cback() if err == nil { return result } } } // Applicationpackage main func main(){ Retry(3, add) }
The retry function receives 2 parameters, one is the number of retry times, and the other is the function that needs to be re-execated. But the functions are all fixed. It can be further optimized.
type Effector func() (string, error) func Retry(count int ,delay , effector){ return func(ctx. )(string, error){ for r:=0; ;r++{ response, err := effector() if err == nil || r>= count { return response, err } ("Function call failed, retrying in %v", delay) select { case <- (delay) case <- (): return "", () } } } }
Add delay parameter delay controls retry delay, uses anonymous function to define a function receiver, and the return value is anonymous function. So the retry function accepts three parameters: an effector, an integer, which describes the number of times the function retrys and the delay between retry.
The parameter of the function receiver is context , which is mainly used to pass context information between goroutines. The context is mainly used here to cancel the timeout and then return quickly.context
Packages mainly provide two ways to createcontext
:
is the default value of the context, and all other contexts should be derived from it.
It should only be used when it is not sure which context should be used;
The above is the more reliable detailed content of using the Go retry mechanism code. For more information about the Go retry mechanism, please pay attention to my other related articles!