demo.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. h "github.com/afex/hystrix-go/hystrix"
  11. y "gopkg.in/yaml.v3"
  12. )
  13. var cmds = map[string]h.CommandConfig{
  14. "defaults": {
  15. Timeout: h.DefaultTimeout,
  16. MaxConcurrentRequests: h.DefaultMaxConcurrent,
  17. RequestVolumeThreshold: h.DefaultVolumeThreshold,
  18. SleepWindow: h.DefaultSleepWindow,
  19. ErrorPercentThreshold: h.DefaultErrorPercentThreshold,
  20. },
  21. "robots": {
  22. Timeout: 100,
  23. MaxConcurrentRequests: 1,
  24. RequestVolumeThreshold: 1,
  25. SleepWindow: 3000,
  26. ErrorPercentThreshold: 1,
  27. },
  28. }
  29. func robots() error {
  30. res, err := http.Get("https://osinet.fr/robots.txt")
  31. if err != nil {
  32. return err
  33. }
  34. if res.StatusCode >= http.StatusBadRequest {
  35. return fmt.Errorf("HTTP Error response: %s", res.Status)
  36. }
  37. b, err := io.ReadAll(res.Body)
  38. if err != nil {
  39. return err
  40. }
  41. fmt.Printf("%s\n", strings.Replace(string(b[0:20]), "\n", "\t", -1))
  42. return nil
  43. }
  44. func robotsFB(e error) error {
  45. ce, ok := e.(h.CircuitError)
  46. if !ok {
  47. return fmt.Errorf("unexpected error: %w", e)
  48. }
  49. switch ce.Message {
  50. case "circuit open":
  51. fmt.Println("FB Short-circuit")
  52. case "timeout":
  53. fmt.Println("FB Timeout response")
  54. default:
  55. log.Println("FB", e.Error())
  56. }
  57. return nil
  58. }
  59. func showCircuitSettings() {
  60. e := y.NewEncoder(os.Stdout)
  61. defer e.Close()
  62. e.SetIndent(2)
  63. fmt.Println(e.Encode(h.GetCircuitSettings()))
  64. }
  65. func showCircuit(name string) {
  66. r, created, err := h.GetCircuit(name)
  67. fmt.Printf("Name: %s, Created it: %t, error: %v\n", r.Name, created, err)
  68. if err == nil {
  69. fmt.Printf("IsOpen: %t, AllowRequest: %t", r.IsOpen(), r.AllowRequest())
  70. }
  71. }
  72. func streamStats() {
  73. sh := h.NewStreamHandler()
  74. sh.Start()
  75. http.Handle("/", sh)
  76. err := http.ListenAndServe(":4000", nil)
  77. fmt.Printf("L&S: %#v\n", err)
  78. sh.Stop()
  79. }
  80. func main() {
  81. h.SetLogger(log.Default())
  82. h.Configure(cmds)
  83. // showCircuit("robots")
  84. // show(h.GetCircuitSettings())
  85. go streamStats()
  86. for i := 0; i < 30; i++ {
  87. t0 := time.Now()
  88. err := h.Do("robots", robots, robotsFB)
  89. d := time.Since(t0)
  90. if err != nil {
  91. fmt.Printf("%2d in %v Error: %v\n", i, d, err)
  92. } else {
  93. fmt.Printf("%2d in %v OK\n", i, d)
  94. }
  95. time.Sleep(1000 * time.Millisecond)
  96. // if i%10 == 0 {
  97. // h.Flush()
  98. // }
  99. }
  100. }