Go微服务实战|第7章:gRPC Deadlines & Timeouts
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
0 条评论
评论者的用户名
评论时间暂时还没有评论.