server.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "hash/crc32"
  7. "io"
  8. "math/rand"
  9. "sync/atomic"
  10. "time"
  11. "go-common/library/ecode"
  12. "go-common/library/log"
  13. "go-common/library/net/rpc/warden"
  14. pb "go-common/library/net/rpc/warden/proto/testproto"
  15. )
  16. var (
  17. req int64
  18. qps int64
  19. cpu int
  20. errRate int
  21. sleep time.Duration
  22. )
  23. func init() {
  24. log.Init(&log.Config{Stdout: false})
  25. flag.IntVar(&cpu, "cpu", 3000, "cpu time")
  26. flag.IntVar(&errRate, "err", 0, "error rate")
  27. flag.DurationVar(&sleep, "sleep", 0, "sleep time")
  28. }
  29. func calcuQPS() {
  30. var creq, breq int64
  31. for {
  32. time.Sleep(time.Second * 5)
  33. creq = atomic.LoadInt64(&req)
  34. delta := creq - breq
  35. atomic.StoreInt64(&qps, delta/5)
  36. breq = creq
  37. fmt.Println("HTTP QPS: ", atomic.LoadInt64(&qps))
  38. }
  39. }
  40. func main() {
  41. flag.Parse()
  42. server := warden.NewServer(nil)
  43. pb.RegisterGreeterServer(server.Server(), &helloServer{})
  44. _, err := server.Start()
  45. if err != nil {
  46. panic(err)
  47. }
  48. calcuQPS()
  49. }
  50. type helloServer struct {
  51. }
  52. func (s *helloServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
  53. atomic.AddInt64(&req, 1)
  54. if in.Name == "err" {
  55. if rand.Intn(100) < errRate {
  56. return nil, ecode.ServiceUnavailable
  57. }
  58. }
  59. time.Sleep(time.Millisecond * time.Duration(in.Age))
  60. time.Sleep(sleep)
  61. for i := 0; i < cpu+rand.Intn(cpu); i++ {
  62. crc32.Checksum([]byte(`testasdwfwfsddsfgwddcscschttp://git.bilibili.co/platform/go-common/merge_requests/new?merge_request%5Bsource_branch%5D=stress%2Fcodel`), crc32.IEEETable)
  63. }
  64. return &pb.HelloReply{Message: "Hello " + in.Name, Success: true}, nil
  65. }
  66. func (s *helloServer) StreamHello(ss pb.Greeter_StreamHelloServer) error {
  67. for i := 0; i < 3; i++ {
  68. in, err := ss.Recv()
  69. if err == io.EOF {
  70. return nil
  71. }
  72. if err != nil {
  73. return err
  74. }
  75. ret := &pb.HelloReply{Message: "Hello " + in.Name, Success: true}
  76. err = ss.Send(ret)
  77. if err != nil {
  78. return err
  79. }
  80. }
  81. return nil
  82. }