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整理维护