教你使用swoole监听redis数据

swoole如何监听redis数据?

Laravel使用swoole监听redis

开始之前,请先确保redis已经正确安装,并正常运行。

Laravel代码

在App\Events目录下新建RedisTest事件

 

message = $message;

    }

    /**

    * Get the channels the event should broadcast on.

    *

    * @return \Illuminate\Broadcasting\Channel|array

    */

    public function broadcastOn()

    {

        return new PrivateChannel('channel-name');

    }

}

  

App\Listeners\RedisTestListener 监听事件代码

message;

        Log::info('the message received from subscribed redis channel msg_0: '.$message);

    }

}
App\Providers\EventServiceProvider 登记事件/监听关系

protected $listen = [

        'App\Events\RedisTest' => [

            'App\Listeners\RedisTestListener',

        ],

    ];

  

监听命令

App\Console\Commands\RedisSubscribe 代码如下

on('message', function (swoole_redis $client, $result) {

            var_dump($result);

            static $more = false;

            if (!$more and $result[0] == 'message')

            {

                echo "trigger Event RedisTest\n";

                Event::fire(new RedisTest($result[2]));

            }

        });

        $client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {

            echo "connect\n";

            $client->subscribe('msg_0');

        });

    }

}

  

Laravel部分代码完成

==================================

supervisor 管理进程

在 /etc/supervisor/conf.d 文件夹下新建 echo.conf , 代码如下

[group:echos]

programs=echo-queue,echo-redis

[program:echo-queue]

command=php artisan queue:work

directory=/home/bella/Downloads/lnmp/echo1.0/echo

user=bella

autorestart=true

redirect_stderr=true

stdout_logfile=/home/bella/Downloads/lnmp/echo1.0/echo/storage/logs/queue.log

loglevel=info

[program:echo-redis]

command=php artisan redis:subscribe

directory=/home/bella/Downloads/lnmp/echo1.0/echo

user=bella

autorestart=true

redirect_stderr=true

stdout_logfile=/home/bella/Downloads/lnmp/echo1.0/echo/storage/logs/redis.log

loglevel=info

  

完成后,执行以下命令重载

supervisorctl reload

=================================

进入redis 客户端,发布一个广播通知到 msg_0 频道

publish msg_0 "Hello Bella"

  

如果 laravel目录下的 storage\logs\laravel.log 最后的日志中记录了广播发送的通知,则redis监听功能实现

你可能感兴趣的:(教你使用swoole监听redis数据)