Skip to content

要並發運行多個 HTTP 服務器,請在 Bun.serve() 中使用 reusePort 選項,該選項可在多個進程間共享同一端口。

這會自動在多個 Bun 實例之間負載均衡傳入的請求。

ts
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("Hello from Bun #" + id + "!\n");
  },
});

NOTE

**僅限 Linux** — Windows 和 macOS 會忽略 `reusePort` 選項。這是操作系統 `SO_REUSEPORT` 的限制,很遺憾。

保存文件後,在同一端口上啟動你的服務器。

在底層,這使用 Linux SO_REUSEPORTSO_REUSEADDR 套接字選項來確保在多個進程間公平負載均衡。了解更多關於 SO_REUSEPORTSO_REUSEADDR

ts
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 模塊,但這是一個更快、更簡單且有限的替代方案。

Bun學習網由www.bunjs.com.cn整理維護