In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Most people do not understand the knowledge points of this article "how to achieve golang fuses", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve golang fuses" article.
The fuse is like a fuse. When there is a problem with the service we rely on, we can be fault-tolerant in time. On the one hand, it can reduce the dependence of the dependent service on its own access and prevent the avalanche effect; on the other hand, it can reduce the request frequency to facilitate the upstream to restore the service as soon as possible.
Fuses are also widely used. In addition to using fuses when requesting services in our applications, there are also a wide range of applications in web gateways and micro services.
1. Mode of fuse
Gobreaker is a Golang implementation based on the fuse pattern in the book Microsoft Cloud Design pattern. There are sony companies open source, the current number of star is 1.2K. The number of users is large.
Here is a state machine defined by the pattern:
Fuses have three states and four states of transition:
Fuse off state, normal service access
Fuse open status, service exception
Fuse half open state, partial request current limit access
Four state transitions:
In the fuse off state, when the fuse fails and certain conditions are met, it will be directly transferred to the fuse open state.
In the fuse open state, if the specified time has passed, it will enter the semi-open state to verify whether the current service is available.
In the fuse semi-open state, if a failure occurs, it will enter the closed state again.
After the fuse is half open and all requests (limited amounts) are successful, the fuse is closed. All requests will be accessed normally.
The realization of 2.gobreaker
Gobreaker is a fuse implemented on the basis of the above state machine.
Definition of fuse type CircuitBreaker struct {name string maxRequests uint32 / / maximum number of requests (current limit in semi-open state) interval time.Duration / / Statistical period timeout time.Duration / / timeout after entering fuse readyToTrip func (counts Counts) bool / / determine whether to turn on fuse by Counts. You need to customize the hook function mutex sync.Mutex / / when the status of onStateChange func (name string, from State, to State) / / is modified. To update the following data, you need to lock state State / / to record which cycle counts Counts / counter the current status generation uint64 / / tag belongs to, and count success, failure, continuous success, continuous failure and so on. Time used to decide whether to enter the fuse expiry time.Time / / to enter the next cycle}
Among them, the following parameters can be customized:
MaxRequests: maximum number of requests. When the maximum number of requests is normal, the fuse will be turned off.
Interval: a normal statistical cycle. If it is 0, the count will be cleared every time.
Timeout: the time that can be requested again after entering the circuit breaker
ReadyToTrip: a hook function for judging the effectiveness of a circuit breaker
OnStateChagne: hook function for state change
2.2 execution of requests
The execution operation of the fuse mainly includes three stages; the decision before the ① request; the request execution of the ② service; and the update of the status and count after the ③ request
/ / call of fuse func (cb * CircuitBreaker) Execute (req func () (interface {}, error)) (interface {}, error) {/ / judgment generation before ① request, err: = cb.beforeRequest () if err! = nil {return nil, err} defer func () {e: = recover () if e! = nil {/ / ③ panic capture cb.afterRequest (generation) False) panic (e)}} () / / ② request and execute result, err: = req () / / ③ update count cb.afterRequest (generation, err = = nil) return result, err} 2.3 decision action before request
The status of the current fuse is determined before the request. If the fuse is turned on, the request will not continue. If the fuse is half open and the maximum request threshold has been reached, the request will not continue.
Func (cb * CircuitBreaker) beforeRequest () (uint64, error) {cb.mutex.Lock () defer cb.mutex.Unlock () now: = time.Now () state, generation: = cb.currentState (now) if state = = StateOpen {/ / fuse open, return return generation directly, ErrOpenState} else if state = = StateHalfOpen & & cb.counts.Requests > = cb.maxRequests {/ / if it is half-open and the number of requests is too many Then directly return return generation, ErrTooManyRequests} cb.counts.onRequest () return generation, nil}
The calculation of the current state is based on the current state. If the current state is turned on, it is determined whether it has timed out, and the timeout can change the state to half-open; if the current state is closed, it is judged whether to enter the next cycle by the cycle.
Func (cb * CircuitBreaker) currentState (now time.Time) (State Uint64) {switch cb.state {case StateClosed: if! cb.expiry.IsZero () & & cb.expiry.Before (now) {/ / whether to enter the next counting cycle cb.toNewGeneration (now)} case StateOpen: if cb.expiry.Before (now) {/ / fuse is changed from open to half-open cb.setState (StateHalfOpen) Now)}} return cb.state, cb.generation}
The length of the cycle is also set according to the current state. If it is currently normal (fuse is off), it is set to a cycle of interval; if the current fuse is on, it is set to timeout (after timeout, it can be changed to half-open state).
2.4 processing operations after the request
After each request, the fuse is counted by whether the request result is successful or not.
Func (cb * CircuitBreaker) afterRequest (before uint64, success bool) {cb.mutex.Lock () defer cb.mutex.Unlock () now: = time.Now () / / if not in a cycle, stop counting state, generation: = cb.currentState (now) if generation! = before {return} if success {cb.onSuccess (state, now)} else {cb.onFailure (state, now)}}
If in a half-open state:
If the request is successful, it will be judged that the current number of consecutive successful requests is greater than or equal to maxRequests, and the state can be changed from half-open to closed.
If the request fails in the half-open state, the half-open state will be transferred to the open state directly.
If in a closed state:
If the request is successful, the count is updated
If the request fails, readyToTrip is called to determine whether the closed state needs to be transferred to the on state.
The above is about the content of this article on "how to achieve golang fuses". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.