Go微服务实战|第7章:gRPC Deadlines & Timeouts

  • 原创
  • Madman
  • /
  • /
  • 0
  • 8536 次阅读

Go 微服务实战.png

Synopsis: 客户端在调用服务端的 RPC 方法时,应该指定超时时间,否则将可能导致客户端资源被耗尽,因为 gRPC 默认使用的超时时间非常长,如果客户端的请求因为某种原因被阻塞了,一旦累计了大量被阻塞的请求后,客户端的资源(比如内存)将可能被耗尽。我们可以在调用 RPC 方法时,传入 context.WithTimeout() 来指定超时时间

代码已上传到 https://github.com/wangy8961/grpc-go-tutorial/tree/v0.7 ,欢迎 star

1. 服务端 RPC 方法模拟长时间才能返回

假设服务端的 UnaryEcho() 方法需要 3 秒以上才能处理完客户端的请求,然后返回结果。如果客户端指定的超时时间少于 3 秒,则客户端接收到的不是正常的响应结果,而是 codes.DeadlineExceeded

创建 grpc-go-tutorial/features/deadline/server/main.go 文件:

// Package main implements a server for Echo service.
package main

import (
    "context"
    "flag"
    "fmt"
    "log"
    "net"
    "time"

    pb "github.com/wangy8961/grpc-go-tutorial/features/echopb"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

// server is used to implement echopb.EchoServer.
type server struct{}

func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
    fmt.Printf("--- gRPC Unary RPC ---\n")
    fmt.Printf("request received: %v\n", req)

    // Suppose it takes a long time to process (3 seconds)
    for i := 0; i < 3; i++ {
        if ctx.Err() == context.Canceled {
            // the client canceled the request
            fmt.Println("The client canceled the request!")
            return nil, status.Errorf(codes.Canceled, "The client canceled the request")
        }
        time.Sleep(1 * time.Second)
    }
    return &pb.EchoResponse{Message: req.GetMessage()}, nil
}

func (s *server) ServerStreamingEcho(req *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
    return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented")
}

func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
    return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented")
}

func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
    return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented")
}

func main() {
    port := flag.Int("port", 50051, "the port to serve on")
    flag.Parse
                                
                            
  • alexander-guan-2839963870
  • 37144698
  • wuleiyzu
  • blake
  • 42952091
  • 31787219
  • jungle
  • chenfan
  • abc127546
  • leon133
  • voidnil0
  • fissh
  • 38198038
  • sailing
  • 2962285897
  • 49666436
  • henry
  • 47849342
  • tomy113
  • 39613212
  • john
  • megangot
  • catherin
  • iyanna
未经允许不得转载: LIFE & SHARE - 王颜公子 » Go微服务实战|第7章:gRPC Deadlines & Timeouts

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.

专题系列