错误描述
grpc默认超时时间是1s,有些框架是500ms,当超时了会报如下错误:
retRobots:,err2:rpc error: code = DeadlineExceeded desc = context deadline exceeded
客户端
- client连接
conn, err := transGrpc.DialInsecure(
context.Background(),
transGrpc.WithEndpoint(grpcClientAddr),
transGrpc.WithTimeout(time.Duration(reqTimeout)*time.Second),
transGrpc.WithMiddleware(middles...))
- controller
func (d HelloWorldController) HelloWorld(ctx context.Context, req *HelloWorldReq) (rsp *HelloWorldRsp, err error) {
userId := ctx.Value(constants.TokenUser).(po.User).Id
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Duration(60*time.Second)))
defer cancel()
if ctx.Err() == context.Canceled {
return nil, status.Errorf(codes.Canceled, "连接服务端超时")
}
ret, err := services.GetHelloWorldService().Get(ctx, userId)
if err == nil {
rsp = &HelloWorldReq{
Code: constants.RespSuccessCode,
Message: constants.RespSuccessMsg,
Data: ret,
}
}
return
}
服务端增加超时
- controller
clientDeadline := time.Now().Add(time.Duration(10 * time.Second))
ctx, cancel := context.WithDeadline(ctx, clientDeadline)
defer cancel()
if ctx.Err() == context.Canceled {
return nil, status.Errorf(codes.Canceled, "客户端已断开")
}
原创文章,作者:站长,如若转载,请注明出处:https://wsppx.cn/1837/%e7%bd%91%e7%bb%9c%e5%bc%80%e5%8f%91/