Bring in grpcs: grpcdeals

  golang, grpc, php, rpc

Bring in grpcs: grpcdeals

Original address:Bring in grpcs: grpcdeals
Project address:https://github.com/EDDYCJY/go …

Preface

In the previous chapters, the basic usage of gRPC has been introduced. Then think about it, is it really okay for him to run naked?

Then, there must be a problem. Today we will introduce the usage of gRPC Deadlines, a necessary skill. The content is also relatively simple

Deadlines

Deadlines refers to the deadline and emphasizes TL in gRPC. Dr (toolong, don’t ‘tread) and suggestedAlways set a deadlineWhy?

Why do you want to set

When Deadlines is not set, the default DEADLINE_EXCEEDED will be used (this time is very large)

If there is a blocking wait, it will cause a large number of ongoing requests to be reserved and all requests are likely to reach the maximum timeout.

This will expose the service to the risk of running out of resources, such as memory, which will increase service latency or, in the worst case, may cause the entire process to crash.

gRPC

Client

func main() {
    ...
    ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Duration(5 * time.Second)))
    defer cancel()

    client := pb.NewSearchServiceClient(conn)
    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)
    }

    log.Printf("resp: %s", resp.GetResponse())
}
  • With deadline: returns the final context.WithDeadline. The first parameter is the parent context and the second parameter is the adjusted deadline. I f the parent time is earlier than the child time, the parent time shall prevail; otherwise, the child time shall be the final deadline.
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
    if cur, ok := parent.Deadline(); ok && cur.Before(d) {
        // The current deadline is already sooner than the new one.
        return WithCancel(parent)
    }
    c := &timerCtx{
        cancelCtx: newCancelCtx(parent),
        deadline:  d,
    }
    propagateCancel(parent, c)
    dur := time.Until(d)
    if dur <= 0 {
        c.cancel(true, DeadlineExceeded) // deadline has already passed
        return c, func() { c.cancel(true, Canceled) }
    }
    c.mu.Lock()
    defer c.mu.Unlock()
    if c.err == nil {
        c.timer = time.AfterFunc(dur, func() {
            c.cancel(true, DeadlineExceeded)
        })
    }
    return c, func() { c.cancel(true, Canceled) }
}
  • With time out: another common method is convenient operation. Actually, it is a package for WithDeadline.
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
    return WithDeadline(parent, time.Now().Add(timeout))
}
  • Status.FromError: Returns the specific error code of GRPCStatus, or directly if it is illegalcodes.Unknown

Server

type SearchService struct{}

func (s *SearchService) Search(ctx context.Context, r *pb.SearchRequest) (*pb.SearchResponse, error) {
    for i := 0; i < 5; i++  {
        if ctx.Err() == context.Canceled {
            return nil, status.Errorf(codes.Canceled, "SearchService.Search canceled")
        }

        time.Sleep(1 * time.Second)
    }

    return &pb.SearchResponse{Response: r.GetRequest() + " Server"}, nil
}

func main() {
    ...
}

On the Server side, the Client has already set a deadline. Server is bound to detect it

Otherwise, if the Client is finished, the Server will still execute there foolishly, which is a great waste of resources.

So it needs to be used here.ctx.Err() == context.CanceledTo judge, we added cycles and sleep to simulate the scene.

Verification

Restart server.go and client.go and get results:

$ go run client.go
2018/10/06 17:45:55 client.Search err: deadline
exit status 1

Summary

This chapter is relatively simple, you need to know the following knowledge points:

  • How to set Deadlines
  • Why do you want to set Deadlines

You should clearly understand that gRPC Deadlines is very important, otherwise this small function point will kill your production.

References

This series of sample codes

Series catalog

data