breaker_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package rpc
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "sync/atomic"
  7. "testing"
  8. "time"
  9. "go-common/library/conf/env"
  10. "go-common/library/ecode"
  11. "go-common/library/log"
  12. "go-common/library/naming"
  13. "go-common/library/naming/discovery"
  14. rcontext "go-common/library/net/rpc/context"
  15. )
  16. func TestBreaker(t *testing.T) {
  17. env.DeployEnv = "dev"
  18. env.Zone = "testzone"
  19. log.Init(&log.Config{Stdout: false})
  20. d := discovery.New(nil)
  21. cancel, err := d.Register(context.TODO(), &naming.Instance{
  22. Zone: "testzone",
  23. Env: "dev",
  24. AppID: "test.appid",
  25. Hostname: "test.host",
  26. Addrs: []string{"gorpc://127.0.0.1:9000"},
  27. Version: "1",
  28. LastTs: time.Now().UnixNano(),
  29. Metadata: map[string]string{"weight": "100"},
  30. })
  31. if err != nil {
  32. panic(err)
  33. }
  34. defer func() {
  35. cancel()
  36. time.Sleep(time.Second)
  37. }()
  38. svr := NewServer(&ServerConfig{Proto: "tcp", Addr: "127.0.0.1:9000"})
  39. err = svr.Register(&BreakerRPC{})
  40. if err != nil {
  41. panic(err)
  42. }
  43. time.Sleep(time.Millisecond * 200)
  44. RunCli()
  45. }
  46. type BreakerReq struct {
  47. Name string
  48. }
  49. type BreakerReply struct {
  50. Success bool
  51. }
  52. type BreakerRPC struct{}
  53. // Ping check connection success.
  54. func (r *BreakerRPC) Ping(c rcontext.Context, arg *BreakerReq, res *BreakerReply) (err error) {
  55. if rand.Int31n(100) < 40 {
  56. return ecode.ServerErr
  57. }
  58. res.Success = true
  59. return
  60. }
  61. func RunCli() {
  62. var success int64
  63. var su int64
  64. var se int64
  65. var other int64
  66. cli := NewDiscoveryCli("test.appid", nil)
  67. for i := 0; i < 1000; i++ {
  68. var res BreakerReply
  69. err := cli.Call(
  70. context.Background(),
  71. "BreakerRPC.Ping",
  72. &BreakerReq{Name: "test"},
  73. &res,
  74. )
  75. if err == nil || ecode.OK.Equal(err) {
  76. atomic.AddInt64(&success, 1)
  77. } else if ecode.ServiceUnavailable.Equal(err) {
  78. atomic.AddInt64(&su, 1)
  79. } else if ecode.ServerErr.Equal(err) {
  80. atomic.AddInt64(&se, 1)
  81. } else {
  82. atomic.AddInt64(&other, 1)
  83. }
  84. time.Sleep(time.Millisecond * 9)
  85. }
  86. fmt.Printf("success:%d su:%d se:%d other:%d \n", success, su, se, other)
  87. }