example_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package breaker_test
  2. import (
  3. "fmt"
  4. "time"
  5. "go-common/library/net/netutil/breaker"
  6. xtime "go-common/library/time"
  7. )
  8. // ExampleGroup show group usage.
  9. func ExampleGroup() {
  10. c := &breaker.Config{
  11. Window: xtime.Duration(3 * time.Second),
  12. Sleep: xtime.Duration(100 * time.Millisecond),
  13. Bucket: 10,
  14. Ratio: 0.5,
  15. Request: 100,
  16. }
  17. // init default config
  18. breaker.Init(c)
  19. // new group
  20. g := breaker.NewGroup(c)
  21. // reload group config
  22. c.Bucket = 100
  23. c.Request = 200
  24. g.Reload(c)
  25. // get breaker by key
  26. g.Get("key")
  27. }
  28. // ExampleBreaker show breaker usage.
  29. func ExampleBreaker() {
  30. // new group,use default breaker config
  31. g := breaker.NewGroup(nil)
  32. brk := g.Get("key")
  33. // mark request success
  34. brk.MarkSuccess()
  35. // mark request failed
  36. brk.MarkFailed()
  37. // check if breaker allow or not
  38. if brk.Allow() == nil {
  39. fmt.Println("breaker allow")
  40. } else {
  41. fmt.Println("breaker not allow")
  42. }
  43. }
  44. // ExampleGo this example create a default group and show function callback
  45. // according to the state of breaker.
  46. func ExampleGo() {
  47. run := func() error {
  48. return nil
  49. }
  50. fallback := func() error {
  51. return fmt.Errorf("unknown error")
  52. }
  53. if err := breaker.Go("example_go", run, fallback); err != nil {
  54. fmt.Println(err)
  55. }
  56. }