Golang Grpc 高级使用
转载请注明来源:https://janrs.com/xag1
Deadlines
超时是分布式系统中常用的一种模式。尽管截止日期与超时相似,但对于gRPC来说,有一个关键的区别。超时是一个选项,让客户决定他们愿意等待服务器响应的时间,并且是在每个客户端本地应用。因此,它不可能在gRPC请求的整个生命周期内应用。这就是为什么我们需要使用截止日期。
超时允许你在微服务架构中避免无限期或长期运行的过程。任何服务都可以查询还有多少时间可以完成RPC,如果超过了这个时间,调用就会以DEADLINE_EXCEEDED错误终止。
Cancellation
gRPC允许客户和服务器都取消他们的请求。客户端和服务器都对调用的成功做出自己的决定。例如,一个GRPC调用可能在服务器端成功完成,但在客户端可能失败。另一方注意到取消,并在RPC被取消时停止其进程。
在Go中,超时和取消功能通过上下文包得到了原生支持。下面是GO中的超时和取消的例子:
Deadlines example in GO
// Setting a deadline
clientDeadline := time.Now().Add(time.Duration(*deadlineMs) * time.Millisecond)
ctx, cancel := context.WithDeadline(ctx, clientDeadline)
// Checking deadline
if ctx.Err() == context.Canceled {
return status.New(codes.Canceled, "Client cancelled, abandoning.")
}
#
Cancellation example in GO
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
cancel()
log.Printf("RPC Status : %s", ctx.Err())
#
Error Handling
gRPC使用一套定义明确的状态代码。这些状态代码、名称和HTTP映射,如以下。
Code | Name | HTTP Mapping |
---|---|---|
0 | OK | 200 OK |
1 | CANCELLED | 499 Client Closed Request |
2 | UNKNOWN | 500 Internal Server Error |
3 | INVALID_ARGUMENT | 400 Bad Request |
4 | DEADLINE_EXCEEDED | 504 Gateway Timeout |
5 | NOT_FOUND | 404 Not Found |
6 | ALREADY_EXISTS | 409 Conflict |
7 | PERMISSION_DENIED | 403 Forbidden |
8 | RESOURCE_EXHAUSTED | 429 Too Many Requests |
9 | FAILED_PRECONDITION | 400 Bad Request |
10 | ABORTED | 409 Conflict |
11 | OUT_OF_RANGE | 400 Bad Request |
12 | UNIMPLEMENTED | 501 Not Implemented |
13 | INTERNAL | 500 Internal Server Error |
14 | UNAVAILABLE | 503 Service Unavailable |
15 | DATA_LOSS | 500 Internal Server Error |
16 | UNAUTHENTICATED | 401 Unauthorized |
Multiplexing
gRPC在很多方面都利用了HTTP/2的优势,其中之一就是多路复用。如你所知,与HTTP/1不同,HTTP/2允许你在同一个TCP连接上发出多个并行请求。我们可以将多路复用定义为gRPC在同一服务器上使用多个服务的能力,并将一个客户端连接用于多个客户端存根。这个功能在有高性能需求的应用中是相当有益的。
Multiplexing example in GO
grpcServer := grpc.NewServer()
// Register Product Service
product_pb.RegisterProductServer(grpcServer, &productServer{})
// Register Billing Service
billing_pb.RegisterBillingServer(grpcServer, &billingServer{})
#
以上简要地总结几个常用的gRPC概念。我希望这些概念在你开发你的gRPC应用时能更加清晰。
转载请注明来源:https://janrs.com/xag1
发表回复