啟動 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 是一種更快速但限制更多的替代方案。