若要並行執行多個 HTTP 伺服器,請在 Bun.serve()
中使用 reusePort
選項,此選項會在多個程序之間共用同一個埠。
這會自動將傳入的請求負載平衡到 Bun 的多個執行個體之間。
import { serve } from "bun";
const id = Math.random().toString(36).slice(2);
serve({
port: process.env.PORT || 8080,
development: false,
// Share the same port across multiple processes
// This is the important part!
reusePort: true,
async fetch(request) {
return new Response("Hello from Bun #" + id + "!\n");
}
});
僅限 Linux — Windows 和 macOS 會忽略 reusePort
選項。這是不幸地,作業系統對於 SO_REUSEPORT
的限制。
儲存檔案後,在同一個埠上啟動您的伺服器。
在底層,這使用 Linux SO_REUSEPORT
和 SO_REUSEADDR
socket 選項,以確保在多個程序之間實現公平的負載平衡。深入瞭解 SO_REUSEPORT
和 SO_REUSEADDR
import { spawn } from "bun";
const cpus = navigator.hardwareConcurrency; // Number of CPU cores
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
模組,但這是一個更快、更簡單且有限的替代方案。