Bun

指南HTTP

使用 Bun 启动 HTTP 服务器集群

通过 "reusePort" 选项并发运行多个 HTTP 服务器,以使多个进程共享同一端口

要并发运行多个 HTTP 服务器,请在 Bun.serve() 中使用 reusePort 选项,该选项可使多个进程共享同一端口。

这将自动将传入请求在多个 Bun 实例之间进行负载均衡。

server.ts
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_REUSEPORTSO_REUSEADDR 套接字选项来确保在多个进程之间实现公平的负载均衡。 详细了解 SO_REUSEPORTSO_REUSEADDR

cluster.ts
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 模块,但这是一种更快、更简单且功能有限的替代方案。