httpclient.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "runtime"
  9. "strconv"
  10. "sync"
  11. "time"
  12. gateway "github.com/rpcxio/rpcx-gateway"
  13. "github.com/smallnest/rpcx/codec"
  14. )
  15. type Args struct {
  16. A int
  17. B int
  18. }
  19. type Reply struct {
  20. C int
  21. }
  22. var (
  23. n = flag.Int("n", 1000, "total requests")
  24. c = flag.Int("c", runtime.GOMAXPROCS(-1), "concurrent")
  25. )
  26. func main() {
  27. flag.Parse()
  28. cc := &codec.MsgpackCodec{}
  29. args := &Args{
  30. A: 10,
  31. B: 20,
  32. }
  33. data, _ := cc.Encode(args)
  34. count := *n / (*c)
  35. var wg sync.WaitGroup
  36. wg.Add(*c)
  37. start := time.Now()
  38. for i := 0; i < *c; i++ {
  39. i := i
  40. go func() {
  41. client := &http.Client{
  42. Transport: &http.Transport{
  43. MaxIdleConnsPerHost: 2000,
  44. },
  45. Timeout: time.Duration(1) * time.Second,
  46. }
  47. req, err := http.NewRequest("POST", "http://127.0.0.1:9981/", bytes.NewReader(data))
  48. if err != nil {
  49. log.Fatal("failed to create request: ", err)
  50. return
  51. }
  52. h := req.Header
  53. h.Set(gateway.XMessageType, "0")
  54. h.Set(gateway.XSerializeType, "3")
  55. h.Set(gateway.XServicePath, "Arith")
  56. h.Set(gateway.XServiceMethod, "Mul")
  57. for j := 0; j < count; j++ {
  58. h.Set(gateway.XMessageID, strconv.Itoa(i*count+j))
  59. req.Body = ioutil.NopCloser(bytes.NewReader(data))
  60. res, err := client.Do(req)
  61. if err != nil {
  62. log.Fatal("failed to call: ", err)
  63. }
  64. defer res.Body.Close()
  65. // handle http response
  66. replyData, err := ioutil.ReadAll(res.Body)
  67. if err != nil {
  68. log.Fatal("failed to read response: ", err)
  69. }
  70. reply := &Reply{}
  71. err = cc.Decode(replyData, reply)
  72. if err != nil {
  73. log.Fatal("failed to decode reply: ", err)
  74. }
  75. //log.Printf("goroutine %d: %d * %d = %d", i, args.A, args.B, reply.C)
  76. }
  77. wg.Done()
  78. }()
  79. }
  80. wg.Wait()
  81. t := time.Since(start).Nanoseconds()
  82. log.Printf("call %d times, took %d ms, tps: %d", *n, t/1e6, uint64(*n)*1e9/uint64(t))
  83. }