Readouble

Laravel 11.x Laravel Reverb

イントロダクションIntroduction

Laravel Reverb(リバーブ:反響)は、高速でスケーラブルなリアルタイムWebSocket通信をLaravelアプリケーションへ直接もたらし、既存のイベントブロードキャストツールスイートとシームレスに統合します。Laravel Reverb[https://github.com/laravel/reverb] brings blazing-fast and scalable real-time WebSocket communication directly to your Laravel application, and provides seamless integration with Laravel’s existing suite of event broadcasting tools[/docs/{{version}}/broadcasting].

インストールInstallation

Reverbのインストールするには、install:broadcasting Artisanコマンドを使用します。You may install Reverb using the install:broadcasting Artisan command:

php artisan install:broadcasting

設定Configuration

install:broadcasting Artisanコマンドは、背後でreverb:installコマンドを実行し、適切なデフォルト設定オプションでReverbをインストールします。設定を変更したい場合は、Reverbの環境変数を更新するか、config/reverb.php設定ファイルを更新してください。Behind the scenes, the install:broadcasting Artisan command will run the reverb:install command, which will install Reverb with a sensible set of default configuration options. If you would like to make any configuration changes, you may do so by updating Reverb's environment variables or by updating the config/reverb.php configuration file.

アプリケーション認証情報Application Credentials

Reverbへの接続を確立するには、クライアントとサーバ間でReverbの「アプリケーション」認証情報を交換する必要があります。この認証情報はサーバ上で設定し、クライアントからのリクエストを確認するために使用します。この認証情報は、以下の環境変数を使用して定義できます。In order to establish a connection to Reverb, a set of Reverb "application" credentials must be exchanged between the client and server. These credentials are configured on the server and are used to verify the request from the client. You may define these credentials using the following environment variables:

REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret

オリジンの許可Allowed Origins

config/reverb.php設定ファイルのappsセクションにある、allowed_origins設定値を更新し、クライアントリクエストの送信元を定義することもできます。許可するオリジンにリストしていないオリジンからのリクエストは拒否します。すべてのオリジンを許可するには、*を使用します。You may also define the origins from which client requests may originate by updating the value of the allowed_origins configuration value within the apps section of the config/reverb.php configuration file. Any requests from an origin not listed in your allowed origins will be rejected. You may allow all origins using *:

'apps' => [
    [
        'id' => 'my-app-id',
        'allowed_origins' => ['laravel.com'],
        // ...
    ]
]

アプリケーションの追加Additional Applications

通常Reverbは、インストール済みのアプリケーション用のWebSocketサーバを提供します。しかし、1つのReverbインストールで、複数のアプリケーションに対応することも可能です。Typically, Reverb provides a WebSocket server for the application in which it is installed. However, it is possible to serve more than one application using a single Reverb installation.

例えば、1つのLaravelアプリケーションを保守しており、Reverbを介して複数のアプリケーションにWebSocket接続を提供したいとしましょう。これは、アプリケーションのconfig/reverb.php設定ファイルへ、複数のappsを定義すれば可能です。For example, you may wish to maintain a single Laravel application which, via Reverb, provides WebSocket connectivity for multiple applications. This can be achieved by defining multiple apps in your application's config/reverb.php configuration file:

'apps' => [
    [
        'app_id' => 'my-app-one',
        // ...
    ],
    [
        'app_id' => 'my-app-two',
        // ...
    ],
],

SSLSSL

ほとんどの場合、セキュアなWebSocket接続は、リクエストがReverbサーバへプロキシされる前に、上流のWebサーバ(Nginxなど)によって処理されます。In most cases, secure WebSocket connections are handled by the upstream web server (Nginx, etc.) before the request is proxied to your Reverb server.

しかし、ローカル開発時などでは、セキュアな接続をReverbサーバが直接処理するのが便利な場合もあります。Laravel Herdのセキュアサイト機能を使用しているか、Laravel Valetを使用していて、アプリケーションに対してsecureコマンドを実行している場合、サイト用に生成されたHerd/Valet証明書を使用して、Reverb接続をセキュアにできます。これを行うには、REVERB_HOST環境変数へサイトのホスト名を設定するか、Reverbサーバの起動時に明示的にホスト名オプションを渡します:However, it can sometimes be useful, such as during local development, for the Reverb server to handle secure connections directly. If you are using Laravel Herd's[https://herd.laravel.com] secure site feature or you are using Laravel Valet[/docs/{{version}}/valet] and have run the secure command[/docs/{{version}}/valet#securing-sites] against your application, you may use the Herd / Valet certificate generated for your site to secure your Reverb connections. To do so, set the REVERB_HOST environment variable to your site's hostname or explicitly pass the hostname option when starting the Reverb server:

php artisan reverb:start --host="0.0.0.0" --port=8080 --hostname="laravel.test"

HerdとValetのドメインはlocalhostで解決されるため、上記のコマンドを実行すると、Reverbサーバはwss://laravel.test:8080のセキュアなWebSocketプロトコル(wss)を介してアクセスできるようになります。Since Herd and Valet domains resolve to localhost, running the command above will result in your Reverb server being accessible via the secure WebSocket protocol (wss) at wss://laravel.test:8080.

アプリケーションのconfig/reverb.php設定ファイルで、tlsオプションを定義して、証明書を手作業で選択することもできます。tlsオプションの配列には、PHPのSSLコンテキストオプションでサポートされているオプションを指定できます。You may also manually choose a certificate by defining tls options in your application's config/reverb.php configuration file. Within the array of tls options, you may provide any of the options supported by PHP's SSL context options[https://www.php.net/manual/en/context.ssl.php]:

'options' => [
    'tls' => [
        'local_cert' => '/path/to/cert.pem'
    ],
],

サーバの実行Running the Server

Reverbサーバは、reverb:start Artisanコマンドで起動できます。The Reverb server can be started using the reverb:start Artisan command:

php artisan reverb:start

Reverbサーバはデフォルトで、0.0.0.0:8080で起動し、すべてのネットワークインターフェイスからアクセスできるようにします。By default, the Reverb server will be started at 0.0.0.0:8080, making it accessible from all network interfaces.

カスタムホストやカスタムポートを指定する必要がある場合は、サーバ起動時に--host--portオプションで指定してください。If you need to specify a custom host or port, you may do so via the --host and --port options when starting the server:

php artisan reverb:start --host=127.0.0.1 --port=9000

もしくは、アプリケーションの.env設定ファイルに、REVERB_SERVER_HOSTREVERB_SERVER_PORT環境変数を定義してください。Alternatively, you may define REVERB_SERVER_HOST and REVERB_SERVER_PORT environment variables in your application's .env configuration file.

REVERB_SERVER_HOSTREVERB_SERVER_PORT環境変数は、REVERB_HOSTREVERB_PORTと混同してはいけません。前者はReverbサーバ自身を実行するホストとポートを指定するのに対し、一方、後者はブロードキャストメッセージの送信先をLaravelへ指示します。例えば、本番環境では、ポート443にある公開Reverbホスト名からのリクエストを、0.0.0.0:8080で動作するReverbサーバにルーティングするとしましょう。この場合、環境変数は以下のように定義します。The REVERB_SERVER_HOST and REVERB_SERVER_PORT environment variables should not be confused with REVERB_HOST and REVERB_PORT. The former specify the host and port on which to run the Reverb server itself, while the latter pair instruct Laravel where to send broadcast messages. For example, in a production environment, you may route requests from your public Reverb hostname on port 443 to a Reverb server operating on 0.0.0.0:8080. In this scenario, your environment variables would be defined as follows:

REVERB_SERVER_HOST=0.0.0.0
REVERB_SERVER_PORT=8080

REVERB_HOST=ws.laravel.com
REVERB_PORT=443

デバッグDebugging

パフォーマンスを向上させるため、Reverbはデフォルトではデバッグ情報を出力しません。Reverbサーバを通過するデータのストリームを見たい場合は、reverb:startコマンドへ--debugオプションを指定してください。To improve performance, Reverb does not output any debug information by default. If you would like to see the stream of data passing through your Reverb server, you may provide the --debug option to the reverb:start command:

php artisan reverb:start --debug

リスタートRestarting

Reverbは実行終了しないプロセスなのため、reverb:restart Artisanコマンドでサーバを再起動しない限り、コードの変更は反映されません。Since Reverb is a long-running process, changes to your code will not be reflected without restarting the server via the reverb:restart Artisan command.

reverb:restartコマンドは、サーバを停止する前にすべての接続を確実に終了させます。Supervisorのようなプロセスマネージャを使い、Reverbを実行している場合は、全ての接続が終了した後、プロセスマネージャによりサーバが自動的に再起動されます:The reverb:restart command ensures all connections are gracefully terminated before stopping the server. If you are running Reverb with a process manager such as Supervisor, the server will be automatically restarted by the process manager after all connections have been terminated:

php artisan reverb:restart

監視Monitoring

Reverbは、Laravel Pulseとの統合により、監視できます。ReverbのPulse統合を有効にすれば、サーバが処理している接続数とメッセージ数を追跡できます。Reverb may be monitored via an integration with Laravel Pulse[/docs/{{version}}/pulse]. By enabling Reverb's Pulse integration, you may track the number of connections and messages being handled by your server.

この統合を有効にするには、まずPulseを確実にインストールしてください。次に、アプリケーションのconfig/pulse.php設定ファイルで、Reverbのレコーダを追加してください。To enable the integration, you should first ensure you have installed Pulse[/docs/{{version}}/pulse#installation]. Then, add any of Reverb's recorders to your application's config/pulse.php configuration file:

use Laravel\Reverb\Pulse\Recorders\ReverbConnections;
use Laravel\Reverb\Pulse\Recorders\ReverbMessages;

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

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

    ...
],

次に、各レコーダーのPulseカードをPulseダッシュボードに追加します。Next, add the Pulse cards for each recorder to your Pulse dashboard[/docs/{{version}}/pulse#dashboard-customization]:

<x-pulse>
    <livewire:reverb.connections cols="full" />
    <livewire:reverb.messages cols="full" />
    ...
</x-pulse>

実機でのReverb実行Running Reverb in Production

WebSocketサーバは長時間稼動するため、Reverbがサーバで利用可能なリソースに対して最適な数の接続を効果的に処理できるように、サーバとホスティング環境を最適化する必要が起きる場合があります。Due to the long-running nature of WebSocket servers, you may need to make some optimizations to your server and hosting environment to ensure your Reverb server can effectively handle the optimal number of connections for the resources available on your server.

lightbulb Note: あなたのサイトをLaravel Forgeで管理している場合、"Application"パネルから直接Reverb用にサーバを自動的に最適化できます。Reverbの統合を有効にすることで、Forgeは必要な拡張機能のインストールや接続許可数の増加など、サーバを本番環境に対応させます。[!NOTE]
If your site is managed by Laravel Forge[https://forge.laravel.com], you may automatically optimize your server for Reverb directly from the "Application" panel. By enabling the Reverb integration, Forge will ensure your server is production-ready, including installing any required extensions and increasing the allowed number of connections.

ファイルオープンOpen Files

各WebSocket接続は、クライアントまたはサーバのどちらかが切断するまでメモリに保持されます。UnixやUnixライクな環境では、各接続はファイルで表されます。しかし、多くの場合、オペレーティング・システムとアプリケーション・レベルの両方で、許可されるファイルオープン数に制限があります。Each WebSocket connection is held in memory until either the client or server disconnects. In Unix and Unix-like environments, each connection is represented by a file. However, there are often limits on the number of allowed open files at both the operating system and application level.

オペレーティングシステムOperating System

Unixベースのオペレーティングシステムでは、ulimitコマンドを使ってオープンできるファイルの数を設定できます。On a Unix based operating system, you may determine the allowed number of open files using the ulimit command:

ulimit -n

このコマンドは、ユーザーごとに許可されているファイルオープンの上限を表示します。これらの値は、/etc/security/limits.confファイルを編集し更新できます。例えば、forgeユーザーのオープンファイルの最大数を10,000に更新するには、以下のようにします。This command will display the open file limits allowed for different users. You may update these values by editing the /etc/security/limits.conf file. For example, updating the maximum number of open files to 10,000 for the forge user would look like the following:

# /etc/security/limits.conf
forge        soft  nofile  10000
forge        hard  nofile  10000

イベントループEvent Loop

Reverbはサーバ上のWebSocket接続を管理するために、ReactPHPのイベントループを使用しています。このイベントループはデフォルトで、stream_selectによって動かされ、追加の拡張は必要ありません。しかし、stream_select は通常、1,024個のファイルオープンに制限されています。そのため、1,000を超える同時接続を処理する場合は、同じ制限に限定されない、別のイベントループを使用する必要があります。Under the hood, Reverb uses a ReactPHP event loop to manage WebSocket connections on the server. By default, this event loop is powered by stream_select, which doesn't require any additional extensions. However, stream_select is typically limited to 1,024 open files. As such, if you plan to handle more than 1,000 concurrent connections, you will need to use an alternative event loop not bound to the same restrictions.

Reverbでは、利用可能な場合には自動的にext-eventext-evext-uvによるループに切り替えます。これらのPHP拡張モジュールは、すべてPECLからインストールできます。Reverb will automatically switch to an ext-event, ext-ev, or ext-uv powered loop when available. All of these PHP extensions are available for install via PECL:

pecl install event
# or
pecl install ev
# or
pecl install uv

WebサーバWeb Server

ほとんどの場合、Reverbはサーバ上のウェブに関係ないポートで実行します。そのため、Reverbへのトラフィックをルーティングするために、リバースプロキシを設定する必要があります。Reverbがホスト0.0.0.0と、ポート8080で動作していて、サーバがNginxウェブサーバと仮定する場合、以下のNginxサイト設定を使用し、リバースプロキシをReverbサーバへ定義できます。In most cases, Reverb runs on a non web-facing port on your server. So, in order to route traffic to Reverb, you should configure a reverse proxy. Assuming Reverb is running on host 0.0.0.0 and port 8080 and your server utilizes the Nginx web server, a reverse proxy can be defined for your Reverb server using the following Nginx site configuration:

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;
    }

    ...
}

通常、Webサーバはサーバの過負荷を防ぐため、許可する接続数を制限するように設定されています。Nginxウェブサーバで許可する接続数を10,000へ増やすには、nginx.confファイルのworker_rlimit_nofileworker_connectionsの値を更新する必要があります。Typically, web servers are configured to limit the number of allowed connections in order to prevent overloading the server. To increase the number of allowed connections on an Nginx web server to 10,000, the worker_rlimit_nofile and worker_connections values of the nginx.conf file should be updated:

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;
}

上記の設定により、1プロセスあたり最大10,000のNginxワーカを生成できるようになります。さらに、この設定は Nginxのファイルオープンの上限を10,000に設定します。The configuration above will allow up to 10,000 Nginx workers per process to be spawned. In addition, this configuration sets Nginx's open file limit to 10,000.

ポートPorts

Unixベースのオペレーティング・システムでは通常、サーバ上でオープンできるポート数を制限しています。現在許可されている範囲は、以下のコマンドで確認できます。Unix-based operating systems typically limit the number of ports which can be opened on the server. You may see the current allowed range via the following command:

cat /proc/sys/net/ipv4/ip_local_port_range
# 32768	60999

各接続が空きポートを必要とするため、上記の出力はサーバが最大28,231個 (60,999-32,768)の接続を処理できることを示しています。水平スケーリングで許容接続数を増やすことを推奨しますが、サーバの/etc/sysctl.conf設定ファイルの許容ポート範囲を更新することで、利用可能なポートオープン数を増やせます。The output above shows the server can handle a maximum of 28,231 (60,999 - 32,768) connections since each connection requires a free port. Although we recommend horizontal scaling[#scaling] to increase the number of allowed connections, you may increase the number of available open ports by updating the allowed port range in your server's /etc/sysctl.conf configuration file.

プロセス管理Process Management

ほとんどの場合、Supervisorなどのプロセスマネージャを使用して、Reverbサーバを確実に持続的に実行する必要があります。Reverbの実行にSupervisorを使用している場合は、サーバのsupervisor.confファイルのminfds設定を更新して、SupervisorがReverbサーバへの接続を処理するために必要なファイルを開けるようにする必要があります。In most cases, you should use a process manager such as Supervisor to ensure the Reverb server is continually running. If you are using Supervisor to run Reverb, you should update the minfds setting of your server's supervisor.conf file to ensure Supervisor is able to open the files required to handle connections to your Reverb server:

[supervisord]
...
minfds=10000

スケーリングScaling

1台のサーバでは処理しきれない数の接続を処理する必要がある場合、Reverbサーバを水平方向に拡張できます。RedisのPub/Sub機能を利用することで、Reverbは複数のサーバにまたがる接続を管理できます。アプリケーションのReverbサーバの1つがメッセージを受信すると、そのサーバはRedisを使用して、受信したメッセージを他のすべてのサーバに公開します。If you need to handle more connections than a single server will allow, you may scale your Reverb server horizontally. Utilizing the publish / subscribe capabilities of Redis, Reverb is able to manage connections across multiple servers. When a message is received by one of your application's Reverb servers, the server will use Redis to publish the incoming message to all other servers.

水平スケーリングを有効にするには、アプリケーションの.env 設定ファイルで、REVERB_SCALING_ENABLED環境変数をtrueに設定します。To enable horizontal scaling, you should set the REVERB_SCALING_ENABLED environment variable to true in your application's .env configuration file:

REVERB_SCALING_ENABLED=true

次に、すべてのReverbサーバが通信する専用の中央Redisサーバを用意します。Reverbは、アプリケーション用に設定したデフォルトのRedis接続を使用して、すべてのReverbサーバへメッセージを公開します。Next, you should have a dedicated, central Redis server to which all of the Reverb servers will communicate. Reverb will use the default Redis connection configured for your application[/docs/{{version}}/redis#configuration] to publish messages to all of your Reverb servers.

一度、Reverbのスケーリングオプションを有効にし、Redisサーバを設定したら、Redisサーバと通信できる複数のサーバ上でreverb:startコマンドを呼び出すだけです。これらのReverbサーバは、入ってくるリクエストをサーバ間で均等に分散させるロードバランサーの後ろに設置すべきです。Once you have enabled Reverb's scaling option and configured a Redis server, you may simply invoke the reverb:start command on multiple servers that are able to communicate with your Redis server. These Reverb servers should be placed behind a load balancer that distributes incoming requests evenly among the servers.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作