API 参考:Drain HTTP 服务器插件
使用此插件
本文档记录了 ApolloServerPluginDrainHttpServer
插件的可选方案,您可以从 @apollo/server/plugin/drainHttpServer
中导入。
此插件旨在与 expressMiddleware
以及其他 框架集成 结合使用,这些框架建立在 Node http.Server
之上。我们强烈推荐使用此插件以确保您的服务器优雅地关闭。
您不需要与 startStandaloneServer
函数一起使用此插件;它自动处理服务器排空。
当您使用此插件时,Apollo Server 将在您调用 stop()
方法(当收到 SIGTERM
和 SIGINT
信号时,这也会为您调用,除非使用 stopOnTerminationSignals
构造函数选项 禁用)时终止您的 HTTP 服务器。
具体来说,它会
- 停止监听新的连接
- 关闭空闲连接(即没有当前 HTTP 请求的连接)
- 一旦活动连接变为空闲,即关闭它们
- 等待所有连接关闭
- 经过一段宽限期后,如果仍有活动连接,将强制关闭它们
此插件由 @apollo/server
包导出。以下是如何与其 Express 一起使用的简单示例:
index.ts
import { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';import express from 'express';import http from 'http';import cors from 'cors';import { typeDefs, resolvers } from './schema';interface MyContext {token?: String;}const app = express();// Our httpServer handles incoming requests to our Express app.// Below, we tell Apollo Server to "drain" this httpServer,// enabling our servers to shut down gracefully.const httpServer = http.createServer(app);const server = new ApolloServer<MyContext>({typeDefs,resolvers,plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});await server.start();app.use('/graphql',cors<cors.CorsRequest>(),express.json(),expressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at https://127.0.0.1:4000/graphql`);
index.js
import { ApolloServer } from '@apollo/server';import { expressMiddleware } from '@apollo/server/express4';import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';import express from 'express';import http from 'http';import cors from 'cors';import { typeDefs, resolvers } from './schema';const app = express();// Our httpServer handles incoming requests to our Express app.// Below, we tell Apollo Server to "drain" this httpServer,// enabling our servers to shut down gracefully.const httpServer = http.createServer(app);const server = new ApolloServer({typeDefs,resolvers,plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],});await server.start();app.use('/graphql',cors(),express.json(),expressMiddleware(server, {context: async ({ req }) => ({ token: req.headers.token }),}),);await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));console.log(`🚀 Server ready at https://127.0.0.1:4000/graphql`);
选项
名称 / 类型 | 描述 |
---|---|
| 要排空的服务器;必需。 |
| 在强制关闭非空闲连接之前需要等待多长时间。默认值为 |