rpc_test.go 1018 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package rpc
  2. import (
  3. "context"
  4. "log"
  5. "os"
  6. "testing"
  7. "time"
  8. "google.golang.org/grpc"
  9. "passport/app/rpc/pb"
  10. "passport/consul"
  11. )
  12. const (
  13. target = "consul://127.0.0.1:8500/im_passport"
  14. defaultName = "world"
  15. )
  16. func TestCallRpc(t *testing.T) {
  17. consul.Init()
  18. // Set up a connection to the server.
  19. ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
  20. conn, err := grpc.DialContext(ctx, target, grpc.WithBlock(), grpc.WithInsecure(), grpc.WithBalancerName("round_robin"))
  21. if err != nil {
  22. log.Fatalf("did not connect: %v", err)
  23. }
  24. defer conn.Close()
  25. c := passportpb.NewPassportClient(conn)
  26. // Contact the server and print out its response.
  27. name := defaultName
  28. if len(os.Args) > 1 {
  29. name = os.Args[1]
  30. }
  31. for {
  32. ctx, _ := context.WithTimeout(context.Background(), time.Second)
  33. r, err := c.SayHello(ctx, &passportpb.HelloRequest{Name: name})
  34. if err != nil {
  35. log.Fatalf("could not greet: %v", err)
  36. }
  37. log.Printf("Greeting: %s", r.Name)
  38. time.Sleep(time.Second * 2)
  39. }
  40. }