breakers.go 1.2 KB

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