miller
发布于

grpc deadline

客户端

ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Duration(5 * time.Second)))
	defer cancel()
........
resp, err := client.Search(ctx, &pb.SearchRequest{
		Request: "gRPC",
	})
	if err != nil {
		statusErr, ok := status.FromError(err)
		if ok {
			if statusErr.Code() == codes.DeadlineExceeded {
				log.Fatalln("client.Search err: deadline")
			}
		}

		log.Fatalf("client.Search err: %v", err)
	}

status.FromError(err) 常用方法。
"google.golang.org/grpc/status"
常用码: codes // import "google.golang.org/grpc/codes"

服务端也要处理: 要不然资源浪费

if ctx.Err() == context.Canceled {
			return nil, status.Errorf(codes.Canceled, "SearchService.Search canceled")
		}
浏览 (298)
点赞
收藏
评论