
[Laravel Reverb]Web APIでWebSocketの接続数を取得する
はじめに
Laravel Pulseと統合してダッシュボードにWebSocketの接続数を表示する方法は公式ドキュメントに記載されていますが、今回はLaravel Pulseは導入せず、シンプルにWeb APIでWebSocketの接続数を取得したかったので、サンプルを作ってみました。
環境
- PHP:8.5.0
- Laravel:12.43.1
- Laravel Reverb:1.6.3
サンプルコード
WebSocketの接続数を取得するコントローラーを作成する
app/Http/Controllers配下にSampleController.phpを作成します。
サンプルなので、コントローラー内でWebSocketの接続数取得まで行っています。
<?php
namespace App\Http\Controllers;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Broadcasting\BroadcastManager;
use Illuminate\Config\Repository;
use Illuminate\Http\JsonResponse;
use Pusher\ApiErrorException;
use Pusher\PusherException;
class SampleController extends Controller
{
public function __construct(
private readonly BroadcastManager $broadcastManager,
private readonly Repository $configRepository
)
{
}
/**
* WebSocketの接続数をJSON形式で返却する
*
* @throws GuzzleException
* @throws PusherException
* @throws ApiErrorException
*
* @return JsonResponse { webSocketCount: int }
*/
public function __invoke(): JsonResponse
{
return response()->json([
'webSocketCount' => $this->getWebSocketConnectionCount()
]);
}
/**
* WebSocketの接続数を取得する
*
* @throws GuzzleException
* @throws PusherException
* @throws ApiErrorException
*
* @return int 接続数
*/
private function getWebSocketConnectionCount(): int
{
// config/reverb.phpのappsから対象アプリケーションの設定を取得
$config = $this->configRepository->get('reverb.apps.apps.0');
// Pusher APIから接続数を取得
return $this->broadcastManager
->pusher($config)
->get('/connections')
->connections;
}
}
routes/web.phpにルーティング定義を追加する
作成したコントローラーのルーティング定義を追加します。
<?php
use Illuminate\Support\Facades\Route;
Route::get('sample', \App\Http\Controllers\SampleController::class);
必要な実装は以上です。
動作確認
/sampleにアクセスしてWebSocketの接続数を取得してみます。
※今回は事前に5つWebSocketのコネクションが確率した状態を準備しました。
{"webSocketCount":5}事前に準備した内容と一致するWebSocketの接続数を取得することができました。
まとめ
今回はWeb APIでWebSocketの接続数を取得するサンプルを作ってみました。
実装自体はシンプルですが、実装に辿り着くまでの調査に時間が掛かった記憶があるので、この記事がどなたかのお役に立てば幸いです。