gRPC超時攔截器實現(xiàn)示例
介紹
本文介紹如何通過 rk-boot 快速搭建 gRPC 超時攔截器。
什么是 gRPC 超時攔截器?
攔截器會攔截 gRPC 請求,并根據策略返回超時錯誤。
安裝
go get github.com/rookie-ninja/rk-boot go get github.com/rookie-ninja/rk-grpc
快速開始
使用 rk-boot 啟動的 gRPC 服務。
支持全局超時和 API 超時設定。
1.創(chuàng)建 boot.yaml
boot.yaml 文件告訴 rk-boot 如何啟動 gRPC 服務。
為了驗證,我們啟動了 commonService,commonService 里包含了一系列常用 API,例如 /rk/v1/gc。
設定全局超時為 5秒,讓 GC 的超時時間定位 1 毫秒,GC 一般會超過 1 毫秒。
---
grpc:
- name: greeter # Required
port: 8080 # Required
enabled: true # Required
commonService:
enabled: true # Optional, Enable common service for testing
interceptors:
timeout:
enabled: true # Optional, default: false
timeoutMs: 5000 # Optional, default: 5000
paths:
- path: "/rk.api.v1.RkCommonService/Gc" # Optional, default: ""
timeoutMs: 1 # Optional, default: 5000
2.創(chuàng)建 main.go
// Copyright (c) 2021 rookie-ninja
//
// Use of this source code is governed by an Apache-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/rookie-ninja/rk-boot"
_ "github.com/rookie-ninja/rk-grpc/boot"
)
// Application entrance.
func main() {
// Create a new boot instance.
boot := rkboot.NewBoot()
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}
3.啟動 main.go
$ go run main.go
4.驗證
發(fā)送 GC 請求。
$ grpcurl -plaintext localhost:8080 rk.api.v1.RkCommonService.Gc
ERROR:
Code: Canceled
Message: Request timed out!
Details:
1) {"@type":"type.googleapis.com/rk.api.v1.ErrorDetail","code":1,"message":"[from-grpc] Request timed out!","status":"Canceled"}
$ curl -X GET localhost:8080/rk/v1/gc
{
"error":{
"code":408,
"status":"Request Timeout",
"message":"Request timed out!",
"details":[
{
"code":1,
"status":"Canceled",
"message":"[from-grpc] Request timed out!"
}
]
}
}以上就是gRPC超時攔截器實現(xiàn)示例的詳細內容,更多關于gRPC超時攔截器的資料請關注腳本之家其它相關文章!
相關文章
Golang實現(xiàn)自己的Redis(有序集合跳表)實例探究
這篇文章主要為大家介紹了Golang實現(xiàn)自己的Redis(有序集合跳表)實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Golang語言JSON解碼函數(shù)Unmarshal的使用
本文主要介紹了Golang語言JSON解碼函數(shù)Unmarshal的使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Golang并發(fā)繞不開的重要組件之Goroutine詳解
Goroutine、Channel、Context、Sync都是Golang并發(fā)編程中的幾個重要組件,這篇文中主要為大家介紹了Goroutine的相關知識,需要的可以參考一下2023-06-06

