前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >gRPC: 实现 gRPC 超时拦截器

gRPC: 实现 gRPC 超时拦截器

原创
作者头像
尹东勋
修改2021-12-13 00:33:22
7340
修改2021-12-13 00:33:22
举报
文章被收录于专栏:开源 & 技术分享

介绍

本文介绍如何通过 rk-boot 快速搭建 gRPC 超时拦截器。

什么是 gRPC 超时拦截器?

拦截器会拦截 gRPC 请求,并根据策略返回超时错误。

请访问如下地址获取完整教程:

安装

代码语言:txt
复制
go get github.com/rookie-ninja/rk-boot
go get github.com/rookie-ninja/rk-grpc

快速开始

使用 rk-boot 启动 gRPC 服务。

支持全局超时和 API 超时设定。

1.创建 boot.yaml

boot.yaml 文件告诉 rk-boot 如何启动 gRPC 服务。

为了验证,我们启动了 commonService,commonService 里包含了一系列常用 API,例如 /rk/v1/gc。

设定全局超时为 5秒,让 GC 的超时时间定位 1 毫秒,GC 一般会超过 1 毫秒。

代码语言:txt
复制
---
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.创建 main.go

代码语言:txt
复制
// 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

代码语言:txt
复制
$ go run main.go

4.验证

发送 GC 请求。

代码语言:txt
复制
$ 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"}
代码语言:txt
复制
$ 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!"
            }
        ]
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 安装
  • 快速开始
    • 1.创建 boot.yaml
      • 2.创建 main.go
        • 3.启动 main.go
          • 4.验证
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档