duanji1899 2018-04-03 02:06
浏览 352

如何在grpc中侦听优美的服务器终止

I want to listen for graceful server termination in grpc in my handler. When the server is being stopped gracefully, I want to add some logic in my code to close open ports, files, flush results etc. How can I do that?

How is it different in case of unary and streaming handler?

  • 写回答

3条回答 默认 最新

  • douxiandiyo58855 2018-04-03 03:22
    关注

    You can have shutdown hook by listening to the signals something like this

    In your main function or where you start your server create channel for signals that you want to listen to

    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)
    

    In your clean up method

    func cleanup(c chan os.Signal) {
       // Wait for termination
       <- c
    
      // Do your cleanups here
    }
    

    Create the signal channel and call the cleanup function as a go routine before you start the gRPC server. Whenever the application (gRPC server) stopped or interrupted this channel will get the signal in the cleanup function where you can do the necessary cleanups

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化