gRPC cleanUp()回调用于golang中的服务器?

xwbd5t1u  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(155)

我想在gRPC服务器停止后立即进行一些清理,例如:

func cleanUp(...) (...) {
  // do something
}

func main() {
  ...
  sOpts := []grpc.ServerOptions{ /* some opts */ }
  sOpts = append(sOpts, grpc.UnaryInterceptor(unaryInterceptor))
  sOpts = append(sOpts, grpc.CleanUpInterceptor(cleanUp))
  s := grpc.NewServer(sOpts...)
  ...
}

有办法做到这一点吗?

ws51t4hk

ws51t4hk1#

您可以使用一个os.Signal来获取gRPC服务器关闭信号,在cleanup拦截器中监视此信号,然后在触发此信号时执行清理作业。
样本代码

sigCh := make(chan os.Signal, 1) 

    cleanUp := func(ctx context.Context, req interface{},
        info *grpc.UnaryServerInfo,
        handler grpc.UnaryHandler) (interface{}, error) {

        select {
        case <-sigCh:
            // do some server shutdown logic
        default:
        }
        h, err := handler(ctx, req)

        return h, err
    }

    sOpts := []grpc.ServerOptions{ /* some opts */ }
    sOpts = append(sOpts, grpc.UnaryInterceptor(unaryInterceptor))
    sOpts = append(sOpts, grpc.UnaryInterceptor(cleanUp))

    signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) // more signal could be added
    s := grpc.NewServer(sOpts...)

相关问题