5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel Echo でRedisのPUB/SUB使ってみた所管

Last updated at Posted at 2016-08-24

イベントをブロードキャストする感じのあれ。

CLIやコントローラ上で発生したイベントを、SocketIO経由でブラウザに投げたり、キューに通知したりするときに使える。

クライアント立てる

WebSocket用のサーバが用意されてる見たいだけど上手く動かなかった。
https://github.com/tlaverdure/laravel-echo-server

のでとりあえずCLIのSUBで試してみる。

以下の内容でsub.jsを作成し node sub.jsで実行。チャンネルを立ち上げる。

var subscriber = require('redis').createClient({
    host: "",
    port: "",
    password:"",
});

subscriber.subscribe('orders');
subscriber.on('message', function(channel, message) {
    console.log('channel: ' + channel + ', message: ' + message);
});

redisはHerokuとかから引っ張ってくると楽。チャンネル名は適当に。

とりあえずredis cliでチャンネルができている事を確認。

$ heroku redis:cli # redis 接続
> pusbub channels
1) orders

Laravel側の用意

config でredisの設定して…BroadcastServiceProvider有効化して、envでBROADCAST_DRIVERredisにして…

まずは、イベントのクラスを作成。

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Message implements ShouldBroadcast
{
    public function broadcastOn()
    {
        return new Channel("orders");
    }
}

ShouldBroadcastを実装する簡単なクラスでOK.

最後にイベントを発行するコマンドを作成する。

<?php
namespace App\Console\Commands;
use App\Events\Message;
use Illuminate\Console\Command;

class Hello extends Command
{
    protected $signature = "hello";

    public function handle(){
        event(new Message());
    }
}

kernel に登録して php artisan helloで完了

立ち上げた node sub.jsの方にイベントの通知が来るはず。

感想

  • Websocketとつなげると色々出来そう
  • laravel-echo-server動かしたい。
  • あとはsocket.ioとredisつなぐだけなのでそんなに難しくはなさそう
  • 認証の機能とかもあるけど、必要だろうか…
  • 後でLumenで試す。
  • PUBはPHPのREST APIで、通知専用のSUBのみNODEというのは運用が楽そう
5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?