k8w / tsrpc

A TypeScript RPC framework, with runtime type checking and serialization, support both HTTP and WebSocket. It is very suitable for website / APP / games, and absolutely comfortable to full-stack TypeScript developers.
MIT License
1.9k stars 203 forks source link

优雅停机tsrpc #16

Closed harochen75 closed 2 years ago

harochen75 commented 2 years ago

怎么做到在停机前,先发送close(reason?: string),告知客户端关闭的原因,然后再进行关闭。

k8w commented 2 years ago
process.on('SIGINT', async function() {
  server.gracefulStop(); // 停止接收新的连接和请求
  await Promise.all(conns.map(v=>v.close('Reason'));  // 告知客户端关闭原因
  process.exit(); // 退出进程
})

有关 gracefulStop 方法的说明(主要针对 HttpServer 短连接),但对于长连接亦会停止接收新的请求:

/**
     * Stop the server gracefully.
     * Wait all API requests finished and then stop the server.
     * @param maxWaitTime - The max time(ms) to wait before force stop the server.
     * `undefined` and `0` means unlimited time.
     */
    gracefulStop(maxWaitTime?: number): Promise<void>