> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Reverb

> 为 Laravel 应用提供实时 WebSocket 通信的官方服务器包。

<Info>
  本页面聚焦于 Reverb 服务器自身的部署与运维。
  关于广播事件的创建以及 Laravel Echo 的使用，请参阅[广播](/zh/broadcasting)。
</Info>

## 什么是 Reverb

[Laravel Reverb](https://github.com/laravel/reverb) 是 Laravel 官方提供的自托管 WebSocket 服务器。
无需依赖外部服务，即可为 Laravel 应用添加高速且可扩展的实时通信。

Reverb 在[广播](/zh/broadcasting)基础之上运行，承担将服务端事件通过 WebSocket 送达浏览器的角色。

```mermaid theme={null}
flowchart LR
    A["浏览器<br>Laravel Echo"] -->|"WebSocket 连接"| B["Laravel Reverb<br>服务器"]
    B -->|"认证/路由"| C["频道<br>管理"]
    C -->|"事件分发"| A
    D["Laravel 应用<br>触发事件"] -->|"广播<br>(经由队列)"| B
```

## 安装

使用 `install:broadcasting` Artisan 命令，可以一次性安装包括 Reverb 在内的所有依赖。

```shell theme={null}
php artisan install:broadcasting
```

执行时可选择 Reverb，或加上 `--reverb` 选项自动完成 Reverb 的配置。

```shell theme={null}
php artisan install:broadcasting --reverb
```

该命令会完成以下工作：

* 安装 Composer 包（`laravel/reverb`）
* 安装 NPM 包（`laravel-echo`、`pusher-js`）
* 向 `.env` 添加环境变量
* 生成 `config/reverb.php`

若手动安装，可先通过 Composer 添加包，然后执行 `reverb:install`。

```shell theme={null}
composer require laravel/reverb
php artisan reverb:install
```

## 配置

### 应用凭据

用于建立客户端与服务器连接的凭据通过环境变量设置。

```ini theme={null}
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
```

这些值会在 `config/reverb.php` 的 `apps` 部分被引用。

### 允许的来源（Allowed Origins）

可以通过 `config/reverb.php` 的 `allowed_origins` 限制允许接入的客户端来源。

```php theme={null}
'apps' => [
    [
        'app_id' => 'my-app-id',
        'allowed_origins' => ['laravel.com'],
        // ...
    ]
]
```

若允许全部来源，请指定 `*`。

### 多应用支持

一台 Reverb 服务器可以同时支持多个应用。
在 `config/reverb.php` 的 `apps` 数组中添加多条条目即可。

```php theme={null}
'apps' => [
    [
        'app_id' => 'my-app-one',
        // ...
    ],
    [
        'app_id' => 'my-app-two',
        // ...
    ],
],
```

### SSL 配置

在生产环境中，通常由 Nginx 等 Web 服务器负责 SSL 终止，再把请求代理到 Reverb。
如果希望在本地开发环境使用安全的 WebSocket（`wss://`），可以利用 Laravel Herd 或 Valet 的证书。

```shell theme={null}
php artisan reverb:start --host="0.0.0.0" --port=8080 --hostname="laravel.test"
```

若要手动指定证书，请在 `config/reverb.php` 中配置 `tls`。

```php theme={null}
'options' => [
    'tls' => [
        'local_cert' => '/path/to/cert.pem'
    ],
],
```

## 启动服务器

使用 `reverb:start` Artisan 命令启动服务器。

```shell theme={null}
php artisan reverb:start
```

默认会以 `0.0.0.0:8080` 启动。
可以通过 `--host` / `--port` 选项自定义地址。

```shell theme={null}
php artisan reverb:start --host=127.0.0.1 --port=9000
```

也可以通过环境变量指定。

```ini theme={null}
REVERB_SERVER_HOST=0.0.0.0
REVERB_SERVER_PORT=8080
```

<Info>
  `REVERB_SERVER_HOST` / `REVERB_SERVER_PORT` 是服务器自身的监听地址。
  `REVERB_HOST` / `REVERB_PORT` 是 Laravel 应用发送广播消息的目标地址。
  在生产环境中这两组值可能不同。
</Info>

### 调试模式

出于性能考虑，Reverb 默认不会输出调试信息。
如果想查看连接与消息流，可以使用 `--debug` 选项。

```shell theme={null}
php artisan reverb:start --debug
```

### 重启服务器

Reverb 是长驻进程，代码变更需要重启才能生效。
`reverb:restart` 命令会先优雅关闭所有连接再停止服务器。

```shell theme={null}
php artisan reverb:restart
```

若使用 Supervisor 等进程管理工具，停止后会自动重启。

## 监控

Reverb 支持与 [Laravel Pulse](https://laravel.com/docs/pulse) 集成。
可以在仪表盘上实时显示连接数和消息数。

首先在 `config/pulse.php` 中添加 Reverb 的 recorder。

```php theme={null}
use Laravel\Reverb\Pulse\Recorders\ReverbConnections;
use Laravel\Reverb\Pulse\Recorders\ReverbMessages;

'recorders' => [
    ReverbConnections::class => [
        'sample_rate' => 1,
    ],

    ReverbMessages::class => [
        'sample_rate' => 1,
    ],

    // ...
],
```

然后在 Pulse 仪表盘模板中添加卡片。

```blade theme={null}
<x-pulse>
    <livewire:reverb.connections cols="full" />
    <livewire:reverb.messages cols="full" />
    ...
</x-pulse>
```

为了正确记录连接情况，请在 Reverb 服务器上启动 `pulse:check` 守护进程。
在水平扩展的部署中，`pulse:check` 仅需在其中一台服务器上运行。

## 生产环境运维

### 文件打开数限制

每个 WebSocket 连接会占用一个文件描述符。
请确认 OS 级别的限制，必要时提升上限。

```shell theme={null}
ulimit -n
```

可以在 `/etc/security/limits.conf` 中修改上限。

```ini theme={null}
# /etc/security/limits.conf
forge        soft  nofile  10000
forge        hard  nofile  10000
```

### 事件循环（ext-uv）

Reverb 默认使用 PHP 的 `stream_select`，其最多支持 1024 个文件。
若要支持 1000 个以上的并发连接，请安装 `ext-uv` 以解除限制。

```shell theme={null}
pecl install uv
```

一旦 `ext-uv` 可用，Reverb 会自动切换到它。

### Nginx 反向代理

生产环境不建议直接暴露 Reverb，而应通过 Nginx 等 Web 服务器代理。
以下是 Nginx 配置示例：

```nginx theme={null}
server {
    ...

    location / {
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";

        proxy_pass http://0.0.0.0:8080;
    }

    ...
}
```

<Warning>
  Reverb 使用 `/app` 处理 WebSocket 连接，使用 `/apps` 处理 API 请求。
  请在 Web 服务器配置中同时允许这两个 URI 的访问。
</Warning>

如需支持更多并发连接，请调整 `nginx.conf` 中的 `worker_rlimit_nofile` 和 `worker_connections`。

```nginx theme={null}
user forge;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
worker_rlimit_nofile 10000;

events {
  worker_connections 10000;
  multi_accept on;
}
```

### 进程管理（Supervisor）

生产环境中建议使用 Supervisor 管理 Reverb 进程。
在 `supervisor.conf` 中设置 `minfds`，以确保获得必要的文件描述符。

```ini theme={null}
[supervisord]
...
minfds=10000
```

Supervisor 配置示例：

```ini theme={null}
[program:reverb]
process_name=%(program_name)s
command=php /path/to/artisan reverb:start
autostart=true
autorestart=true
user=forge
redirect_stderr=true
stdout_logfile=/path/to/reverb.log
```

### 扩展（Redis）

单台服务器无法承载所需连接量时，可以使用 Redis 的 pub/sub 功能进行水平扩展。

```mermaid theme={null}
flowchart TB
    LB["负载均衡器"] --> R1["Reverb 服务器 1"]
    LB --> R2["Reverb 服务器 2"]
    LB --> R3["Reverb 服务器 3"]
    R1 <-->|"pub/sub"| Redis["Redis"]
    R2 <-->|"pub/sub"| Redis
    R3 <-->|"pub/sub"| Redis
```

在 `.env` 中启用扩展。

```env theme={null}
REVERB_SCALING_ENABLED=true
```

Reverb 会使用应用默认的 Redis 连接在多台服务器之间转发消息。
启动多台 Reverb 服务器，通过负载均衡分发请求即可。

<Info>
  [Laravel Cloud](https://cloud.laravel.com) 提供了完全托管的 WebSocket 基础设施，可以无需自行运维基础设施即可部署基于 Reverb 的应用。
</Info>

## 事件

Reverb 在连接与消息的生命周期中会派发以下事件。
你可以通过[事件监听器](/zh/events)接收它们并添加自定义处理。

| 事件                 | 说明               |
| ------------------ | ---------------- |
| `ChannelCreated`   | 频道被创建（首个连接订阅时）   |
| `ChannelRemoved`   | 频道被删除（最后一个连接退订时） |
| `ConnectionPruned` | 服务器清理陈旧连接时       |
| `MessageReceived`  | 收到客户端消息时         |
| `MessageSent`      | 向客户端发送消息时        |

这些事件都属于 `Laravel\Reverb\Events` 命名空间。

## 下一步

<Card title="广播" href="/zh/broadcasting">
  了解广播事件的创建、频道授权以及 Laravel Echo 的配置。
</Card>

<Card title="事件与监听器" href="/zh/events">
  学习用于接收 Reverb 事件的 Laravel 事件系统。
</Card>


## Related topics

- [广播](/zh/broadcasting.md)
- [Laravel 11 之后新应用结构 FAQ](/zh/advanced/app-structure-faq.md)
- [部署](/zh/deployment.md)
- [Laravel Cloud — Laravel 专用 PaaS 全貌](/zh/blog/laravel-cloud.md)
- [2026 年 3 月 Laravel 更新](/zh/blog/changelog/202603.md)
