GRPC set of client timeout (golang)

In use grpc time encountered a problem: how to set the timeout client-side Internet search a large circle, not too obvious example?.

Here we look at look at the helloworld example grpc:

client

1
2
3
4
5
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
func main() {  // Set up a connection to the server.  conn, err := grpc.Dial(address, grpc.WithInsecure())  if err != nil {  log.Fatalf("did not connect: %v", err)  }  defer conn.Close()  c := pb.NewGreeterClient(conn)   // Contact the server and print out its response.  name := defaultName  if len(os.Args) > 1 {  name = os.Args[1]  }  r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})  if err != nil {  log.Fatalf("could not greet: %v", err)  }  log.Printf("Greeting: %s", r.Message) } 

With a little bit SayHelloof calls, and finally the call to invokethe function:

google.golang.org/grpc/call.go

1
2
3
4
5
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) {  c := defaultCallInfo  mc := cc.GetMethodConfig(method)  if mc.WaitForReady != nil {  c.failFast = !*mc.WaitForReady  }   // 值得注意  if mc.Timeout != nil && *mc.Timeout >= 0 {  var cancel context.CancelFunc  ctx, cancel = context.WithTimeout(ctx, *mc.Timeout)  defer cancel()  }   opts = append(cc.dopts.callOptions, opts...)  for _, o := range opts {  if err := o.before(&c); err != nil {  return toRPCErr(err)  }  }  defer func() {  for _, o := range opts {  o.after(&c)  }  }() 

It is worth noting that context timeout setting carefully read the document under the context of, you will find there are corresponding context timeout setting:

WithTimeout

1
2
3
4
5
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
package main

import (  "context"  "fmt"  "time" )  func main() {  // Pass a context with a timeout to tell a blocking function that it  // should abandon its work after the timeout elapses.  ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)  defer cancel()   select {  case <-time.After(1 * time.Second):  fmt.Println("overslept")  case <-ctx.Done():  fmt.Println(ctx.Err()) // prints "context deadline exceeded"  } } 

We try to set the context of a timeout before the client calls:

client

1
2
3
4
5
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
func main() {  // Set up a connection to the server.  conn, err := grpc.Dial(address, grpc.WithInsecure())  if err != nil {  log.Fatalf("did not connect: %v", err)  }  defer conn.Close()  c := pb.NewGreeterClient(conn)   // Contact the server and print out its response.  name := defaultName  if len(os.Args) > 1 {  name = os.Args[1]  }   // 改一下  ctx, cancel := context.WithTimeout(context.Background(), 100 * time.Millisecond)  defer cancel()  r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})  if err != nil {  log.Fatalf("could not greet: %v", err)  }  log.Printf("Greeting: %s", r.Message) } 

In order to ensure a timeout, a break in the sever code:

server

1
2
3
4
5
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {  time.Sleep(1 * time.Second)  return &pb.HelloReply{Message: "Hello " + in.Name}, nil } 

Two were running client and server programs, you will see client-side printing:

1
could not greet: rpc error: code = DeadlineExceeded desc = context deadline exceeded

Guess you like

Origin www.cnblogs.com/ExMan/p/12119025.html