本文将介绍优雅关闭 gRPC 微服务。
什么是优雅关闭?
在进程收到关闭信号时,我们需要关闭后台运行的逻辑,比如,MySQL 连接等等。
我们将会使用 rk-boot 来启动 gRPC 服务。
请访问如下地址获取完整教程:
go get github.com/rookie-ninja/rk-boot
go get github.com/rookie-ninja/rk-grpc
---
grpc:
- name: greeter # Name of grpc entry
port: 8080 # Port of grpc entry
enabled: true # Enable grpc entry
通过 AddShutdownHookFunc() 来添加 shutdownhook 函数。
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()
// Add shutdown hook function
boot.AddShutdownHookFunc("shutdown-hook", func() {
fmt.Println("shutting down")
})
// Bootstrap
boot.Bootstrap(context.Background())
// Wait for shutdown sig
boot.WaitForShutdownSig(context.Background())
}
$ go run main.go
通过 ctrl-c 关闭程序,我们会看到打印如下信息。
shutting down
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。