You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/breaker/breakers.go

69 lines
1.6 KiB
Go

4 years ago
package breaker
import "sync"
var (
lock sync.RWMutex
breakers = make(map[string]Breaker)
)
// Do calls Breaker.Do on the Breaker with given name.
4 years ago
func Do(name string, req func() error) error {
return do(name, func(b Breaker) error {
return b.Do(req)
})
}
// DoWithAcceptable calls Breaker.DoWithAcceptable on the Breaker with given name.
4 years ago
func DoWithAcceptable(name string, req func() error, acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithAcceptable(req, acceptable)
})
}
// DoWithFallback calls Breaker.DoWithFallback on the Breaker with given name.
func DoWithFallback(name string, req func() error, fallback Fallback) error {
4 years ago
return do(name, func(b Breaker) error {
return b.DoWithFallback(req, fallback)
})
}
// DoWithFallbackAcceptable calls Breaker.DoWithFallbackAcceptable on the Breaker with given name.
func DoWithFallbackAcceptable(name string, req func() error, fallback Fallback,
4 years ago
acceptable Acceptable) error {
return do(name, func(b Breaker) error {
return b.DoWithFallbackAcceptable(req, fallback, acceptable)
})
}
// GetBreaker returns the Breaker with the given name.
4 years ago
func GetBreaker(name string) Breaker {
lock.RLock()
b, ok := breakers[name]
lock.RUnlock()
if ok {
return b
}
lock.Lock()
b, ok = breakers[name]
if !ok {
b = NewBreaker(WithName(name))
breakers[name] = b
}
lock.Unlock()
4 years ago
4 years ago
return b
}
// NoBreakerFor disables the circuit breaker for the given name.
func NoBreakerFor(name string) {
4 years ago
lock.Lock()
breakers[name] = newNopBreaker()
4 years ago
lock.Unlock()
}
func do(name string, execute func(b Breaker) error) error {
return execute(GetBreaker(name))
4 years ago
}