breakers.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package breaker
  2. import "sync"
  3. var (
  4. lock sync.RWMutex
  5. breakers = make(map[string]Breaker)
  6. )
  7. // Do calls Breaker.Do on the Breaker with given name.
  8. func Do(name string, req func() error) error {
  9. return do(name, func(b Breaker) error {
  10. return b.Do(req)
  11. })
  12. }
  13. // DoWithAcceptable calls Breaker.DoWithAcceptable on the Breaker with given name.
  14. func DoWithAcceptable(name string, req func() error, acceptable Acceptable) error {
  15. return do(name, func(b Breaker) error {
  16. return b.DoWithAcceptable(req, acceptable)
  17. })
  18. }
  19. // DoWithFallback calls Breaker.DoWithFallback on the Breaker with given name.
  20. func DoWithFallback(name string, req func() error, fallback func(err error) error) error {
  21. return do(name, func(b Breaker) error {
  22. return b.DoWithFallback(req, fallback)
  23. })
  24. }
  25. // DoWithFallbackAcceptable calls Breaker.DoWithFallbackAcceptable on the Breaker with given name.
  26. func DoWithFallbackAcceptable(name string, req func() error, fallback func(err error) error,
  27. acceptable Acceptable) error {
  28. return do(name, func(b Breaker) error {
  29. return b.DoWithFallbackAcceptable(req, fallback, acceptable)
  30. })
  31. }
  32. // GetBreaker returns the Breaker with the given name.
  33. func GetBreaker(name string) Breaker {
  34. lock.RLock()
  35. b, ok := breakers[name]
  36. lock.RUnlock()
  37. if ok {
  38. return b
  39. }
  40. lock.Lock()
  41. b, ok = breakers[name]
  42. if !ok {
  43. b = NewBreaker(WithName(name))
  44. breakers[name] = b
  45. }
  46. lock.Unlock()
  47. return b
  48. }
  49. // NoBreakerFor disables the circuit breaker for the given name.
  50. func NoBreakerFor(name string) {
  51. lock.Lock()
  52. breakers[name] = newNoOpBreaker()
  53. lock.Unlock()
  54. }
  55. func do(name string, execute func(b Breaker) error) error {
  56. return execute(GetBreaker(name))
  57. }