如何在grpc中监听优雅的服务器终止

问题描述 投票:1回答:3

我想在我的处理程序中监听grpc中优雅的服务器终止。当服务器正常停止时,我想在我的代码中添加一些逻辑来关闭打开的端口,文件,刷新结果等。我该怎么做?

在一元和流处理程序的情况下它有什么不同?

go grpc
3个回答
0
投票

你可以通过听这样的信号来关闭钩子

在您的主要功能或启动服务器的位置为您想要收听的信号创建通道

c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
// call your cleanup method with this channel as a routine
go cleanup(c)

在你的清理方法

func cleanup(c chan os.Signal) {
   // Wait for termination
   <- c

  // Do your cleanups here
}

在启动gRPC服务器之前,创建信号通道并将cleanup函数作为go例程调用。每当应用程序(gRPC服务器)停止或中断时,此通道将获取cleanup函数中的信号,您可以在其中进行必要的清理


0
投票

目前没有机制向服务处理程序发出关于Graceful stop的信号。在服务器退出时必须发生的清理和其他此类全局功能通常不会发生在服务处理程序内部。也就是说,如果你认为你的设计在服务处理程序内部发生这种清理会更好,并且来自优雅关闭的信号是至关重要的,我们希望能够更多地了解您的用例。也许在我们的github repo上打开一个问题,我们可以在那里讨论它。

最好,

母亲


0
投票

对于grpc服务器,你可以这样做

func waitForGracefulShutdown(srv *grpc.Server) {
fmt.Println("Grpc messaging server started ...")
interruptChan := make(chan os.Signal, 1)
signal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

// Block until we receive our signal.
<-interruptChan

// Create a deadline to wait for.
_, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
srv.GracefulStop()
publisher, messagingError := messaging.GetPublisherInstance()
if messagingError.Error == nil {
    publisher.Close()
}

log.Println("Shutting down grpc messaging server.")
os.Exit(0)

}

© www.soinside.com 2019 - 2024. All rights reserved.