本篇介紹如何在 Laravel 框架中,使用官方內建的 Laravel Reverb 實作 WebSocket 即時通訊。
什麼是 Laravel Reverb?
Laravel Reverb 是 Laravel 官方在 11.x 版本推出的第一方 WebSocket 伺服器套件,不再需要依賴第三方套件(如 beyondcode/laravel-websockets)即可建立 WebSocket 服務。
相比過去需要搭配 Pusher 或自架 laravel-websockets,Reverb 的優勢在於:
- 原生整合 Laravel Broadcasting 系統
- 效能更佳,支援大量並發連線
- 設定更簡單,開箱即用
- 支援 horizontal scaling(水平擴展)
環境需求
- PHP >= 8.2
- Laravel >= 11.x
安裝 Laravel Reverb
# 安裝 Reverb(Laravel 11+)
php artisan install:broadcasting
執行後 Laravel 會自動:
- 安裝
laravel/reverb套件 - 發布設定檔
config/reverb.php - 在
.env新增相關變數 - 安裝前端套件
laravel-echo與pusher-js
設定 .env
# .env
BROADCAST_CONNECTION=reverb
REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret
REVERB_HOST="localhost"
REVERB_PORT=8080
REVERB_SCHEME=http
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"
建立 Event
建立一個可廣播的 Event,這裡以聊天訊息為例:
php artisan make:event MessageSent
# app/Events/MessageSent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(
public string $message,
public string $user,
) {}
public function broadcastOn(): array
{
return [
new Channel('chat'),
];
}
public function broadcastAs(): string
{
return 'message.sent';
}
}
建立 Controller 觸發廣播
# app/Http/Controllers/ChatController.php
<?php
namespace App\Http\Controllers;
use App\Events\MessageSent;
use Illuminate\Http\Request;
class ChatController extends Controller
{
public function send(Request $request)
{
$request->validate([
'message' => 'required|string|max:500',
]);
broadcast(new MessageSent(
message: $request->message,
user: $request->user()->name ?? 'Guest',
));
return response()->json(['status' => 'ok']);
}
}
設定 routes/web.php
Route::post('/chat/send', [ChatController::class, 'send'])->middleware('auth');
前端設定(使用 Laravel Echo + Reverb)
# resources/js/echo.js
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'reverb',
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: import.meta.env.VITE_REVERB_PORT,
wssPort: import.meta.env.VITE_REVERB_PORT,
forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
enabledTransports: ['ws', 'wss'],
});
監聽頻道事件:
window.Echo.channel('chat')
.listen('.message.sent', (e) => {
console.log(e.user + ': ' + e.message);
});
啟動 Reverb Server
# 啟動 WebSocket Server(預設 port: 8080) php artisan reverb:start # 指定 host / port php artisan reverb:start --host=0.0.0.0 --port=8080 # 開發模式(顯示連線 debug 訊息) php artisan reverb:start --debug
使用 Supervisor 管理 Reverb 進程
正式環境建議使用 Supervisor 讓 Reverb 常駐執行,避免意外中斷:
# /etc/supervisor/conf.d/reverb.conf
[program:reverb]
command=php /var/www/html/artisan reverb:start --host=0.0.0.0 --port=8080
numprocs=1
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/supervisor/reverb.log
supervisorctl reread supervisorctl update supervisorctl start reverb
Reverb 與 beyondcode/laravel-websockets 比較
| 項目 | Reverb(官方) | laravel-websockets |
|---|---|---|
| 維護單位 | Laravel 官方 | 第三方 (Beyond Code) |
| 支援 Laravel 版本 | 11.x+ | 8.x ~ 10.x |
| 效能 | 較高(非同步 I/O) | 一般 |
| 水平擴展 | 支援(Redis Pub/Sub) | 有限支援 |
| 安裝複雜度 | 低 | 中 |
小結
Laravel Reverb 是 Laravel 11 之後的首選 WebSocket 方案,若你還在用 beyondcode/laravel-websockets,可以考慮隨著升版一起遷移。整個安裝流程只需要一個 artisan 指令就能完成,搭配 Supervisor 即可讓 WebSocket 服務穩定常駐。
參考文獻: