Go gRPC進(jìn)階-超時設(shè)置(六)
前言
gRPC默認(rèn)的請求的超時時間是很長的,當(dāng)你沒有設(shè)置請求超時時間時,所有在運(yùn)行的請求都占用大量資源且可能運(yùn)行很長的時間,導(dǎo)致服務(wù)資源損耗過高,使得后來的請求響應(yīng)過慢,甚至?xí)鹫麄€進(jìn)程崩潰。
為了避免這種情況,我們的服務(wù)應(yīng)該設(shè)置超時時間。前面的入門教程提到,當(dāng)客戶端發(fā)起請求時候,需要傳入上下文context.Context,用于結(jié)束超時或取消的請求。
本篇以簡單RPC為例,介紹如何設(shè)置gRPC請求的超時時間。
客戶端請求設(shè)置超時時間
修改調(diào)用服務(wù)端方法
1.把超時時間設(shè)置為當(dāng)前時間+3秒
clientDeadline := time.Now().Add(time.Duration(3 * time.Second))
ctx, cancel := context.WithDeadline(ctx, clientDeadline)
defer cancel()
2.響應(yīng)錯誤檢測中添加超時檢測
// 傳入超時時間為3秒的ctx
res, err := grpcClient.Route(ctx, &req)
if err != nil {
//獲取錯誤狀態(tài)
statu, ok := status.FromError(err)
if ok {
//判斷是否為調(diào)用超時
if statu.Code() == codes.DeadlineExceeded {
log.Fatalln("Route timeout!")
}
}
log.Fatalf("Call Route err: %v", err)
}
// 打印返回值
log.Println(res.Value)
完整的client.go代碼
服務(wù)端判斷請求是否超時
當(dāng)請求超時后,服務(wù)端應(yīng)該停止正在進(jìn)行的操作,避免資源浪費(fèi)。
// Route 實(shí)現(xiàn)Route方法
func (s *SimpleService) Route(ctx context.Context, req *pb.SimpleRequest) (*pb.SimpleResponse, error) {
data := make(chan *pb.SimpleResponse, 1)
go handle(ctx, req, data)
select {
case res := <-data:
return res, nil
case <-ctx.Done():
return nil, status.Errorf(codes.Canceled, "Client cancelled, abandoning.")
}
}
func handle(ctx context.Context, req *pb.SimpleRequest, data chan<- *pb.SimpleResponse) {
select {
case <-ctx.Done():
log.Println(ctx.Err())
runtime.Goexit() //超時后退出該Go協(xié)程
case <-time.After(4 * time.Second): // 模擬耗時操作
res := pb.SimpleResponse{
Code: 200,
Value: "hello " + req.Data,
}
// //修改數(shù)據(jù)庫前進(jìn)行超時判斷
// if ctx.Err() == context.Canceled{
// ...
// //如果已經(jīng)超時,則退出
// }
data <- &res
}
}
一般地,在寫庫前進(jìn)行超時檢測,發(fā)現(xiàn)超時就停止工作。
完整server.go代碼
運(yùn)行結(jié)果
服務(wù)端:
:8000 net.Listing...
goroutine still running
客戶端:
Route timeout!
總結(jié)
超時時間的長短需要根據(jù)自身服務(wù)而定,例如返回一個hello grpc,可能只需要幾十毫秒,然而處理大量數(shù)據(jù)的同步操作則可能要很長時間。需要考慮多方面因素來決定這個超時時間,例如系統(tǒng)間端到端的延時,哪些RPC是串行的,哪些是可以并行的等等。
教程源碼地址:https://github.com/Bingjian-Zhu/go-grpc-example
參考:https://grpc.io/blog/deadlines/
看完之后若覺得對自己有幫助,懇請點(diǎn)贊或評論。這是對我最大的鼓勵!

浙公網(wǎng)安備 33010602011771號