Skip to main content
要并发运行多个 HTTP 服务器,可以在 Bun.serve() 中使用 reusePort 选项,该选项允许多个进程共享同一个端口。 这将自动在多个 Bun 实例之间负载均衡传入的请求。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79server.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("来自 Bun #" + id + " 的问候!\n");
  },
});

仅限 Linux — Windows 和 macOS 会忽略 reusePort 选项。这是操作系统对 SO_REUSEPORT 的限制,遗憾的是如此。
保存文件后,在相同端口启动服务器。 底层使用了 Linux 的 SO_REUSEPORTSO_REUSEADDR 套接字选项,确保多个进程之间的公平负载均衡。 了解有关 SO_REUSEPORTSO_REUSEADDR 的更多信息
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cluster.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 模块,但这是一个更快、更简单且功能有限的替代方案。