exapmle_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package warden_test
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "time"
  7. "go-common/library/log"
  8. "go-common/library/net/netutil/breaker"
  9. "go-common/library/net/rpc/warden"
  10. pb "go-common/library/net/rpc/warden/proto/testproto"
  11. xtime "go-common/library/time"
  12. "google.golang.org/grpc"
  13. )
  14. type helloServer struct {
  15. }
  16. func (s *helloServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
  17. return &pb.HelloReply{Message: "Hello " + in.Name, Success: true}, nil
  18. }
  19. func (s *helloServer) StreamHello(ss pb.Greeter_StreamHelloServer) error {
  20. for i := 0; i < 3; i++ {
  21. in, err := ss.Recv()
  22. if err == io.EOF {
  23. return nil
  24. }
  25. if err != nil {
  26. return err
  27. }
  28. ret := &pb.HelloReply{Message: "Hello " + in.Name, Success: true}
  29. err = ss.Send(ret)
  30. if err != nil {
  31. return err
  32. }
  33. }
  34. return nil
  35. }
  36. func ExampleServer() {
  37. s := warden.NewServer(&warden.ServerConfig{Timeout: xtime.Duration(time.Second), Addr: ":8080"})
  38. // apply server interceptor middleware
  39. s.Use(func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
  40. newctx, cancel := context.WithTimeout(ctx, time.Second*10)
  41. defer cancel()
  42. resp, err := handler(newctx, req)
  43. return resp, err
  44. })
  45. pb.RegisterGreeterServer(s.Server(), &helloServer{})
  46. s.Start()
  47. }
  48. func ExampleClient() {
  49. client := warden.NewClient(&warden.ClientConfig{
  50. Dial: xtime.Duration(time.Second * 10),
  51. Timeout: xtime.Duration(time.Second * 10),
  52. Breaker: &breaker.Config{
  53. Window: xtime.Duration(3 * time.Second),
  54. Sleep: xtime.Duration(3 * time.Second),
  55. Bucket: 10,
  56. Ratio: 0.3,
  57. Request: 20,
  58. },
  59. })
  60. // apply client interceptor middleware
  61. client.Use(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (ret error) {
  62. newctx, cancel := context.WithTimeout(ctx, time.Second*5)
  63. defer cancel()
  64. ret = invoker(newctx, method, req, reply, cc, opts...)
  65. return
  66. })
  67. conn, err := client.Dial(context.Background(), "127.0.0.1:8080")
  68. if err != nil {
  69. log.Error("did not connect: %v", err)
  70. return
  71. }
  72. defer conn.Close()
  73. c := pb.NewGreeterClient(conn)
  74. name := "2233"
  75. rp, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name, Age: 18})
  76. if err != nil {
  77. log.Error("could not greet: %v", err)
  78. return
  79. }
  80. fmt.Println("rp", *rp)
  81. }