启动 HTTP 服务器集群
使用“reusePort”选项并发运行多个 HTTP 服务器,使多个进程共享同一端口
要并发运行多个 HTTP 服务器,请在 Bun.serve() 中使用 reusePort 选项。它可以让多个进程共享一个端口,并在这些进程之间对传入请求进行负载均衡。
import { serve } from "bun";
const id = Math.random().toString(36).slice(2);
serve({
port: process.env.PORT || 8080,
development: false,
// 多个进程共享同一端口
// 这是关键部分!
reusePort: true,
async fetch(request) {
return new Response("来自 Bun #" + id + " 的问候!\n");
},
});
保存文件后,在相同端口启动服务器。
reusePort 使用 Linux 的 SO_REUSEPORT 和 SO_REUSEADDR 套接字选项,以确保在多个进程之间进行公平的负载均衡。详细了解 SO_REUSEPORT 和 SO_REUSEADDR
import { spawn } from "bun";
const cpus = navigator.hardwareConcurrency; // CPU 核心数
const buns = new Array(cpus);
for (let i = 0; i < cpus; i++) {
buns[i] = spawn({
cmd: ["bun", "./server.ts"],
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
});
}
function kill() {
for (const bun of buns) {
bun.kill();
}
}
process.on("SIGINT", kill);
process.on("exit", kill);
Bun 还实现了 node:cluster 模块;reusePort 是一种更快速但限制更多的替代方案。