关于laravel5 消息订阅/发布的理解初

laravel5.4
感受官网文档说滴不够详细...安装predis官网很详细,这里略过....php

生成命令

直接使用 Artisan 命令 make:command,该命令会在 app/Console/Commands 目录下建立一个新的命令类。若是该目录不存在,不用担忧,它将会在你首次运行 Artisan 命令 make:command 时被建立。生成的命令将会包含默认的属性设置以及全部命令都共有的方法,laravel

这里我生成一个RedisSubscribe.php类,执行下面命令:web

php artisan make:command RedisSubscribe

引用官网上说的redis

Redis 还提供了调用 Redis 的publish 和 subscribe 命令的接口。这些 Redis 命令容许你在给定“频道”监听消息,你能够从另一个应用发布消息到这个频道,甚至使用其它编程语言,从而容许你在不一样的应用/进程之间轻松通讯。

首先,让咱们使用 subscribe 方法经过 Redis 在一个频道上设置监听器。因为调用 subscribe 方法会开启一个常驻进程,咱们将在 Artisan 命令中调用该方法:

redis必须开启一个轮询监听频道滴服务进程,也就是上面说的 在 Artisan 命令中调用,如何调用?稍后测试下,
执行上诉命令后会看到:编程

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class RedisSubscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Subscribe to a Redis channel';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Redis::psubscribe(['user-channel'], function($message) {
            echo $message;
        });
    }
}
$signature 这里的配置会执行如下命名后看到:
php artisan list

好比我滴是:
json

如今,咱们可使用 publish 发布消息到该频道:数组

在执行如下代码前 如今控制台中输入:php artisan redis:subscribe 启动服务进程浏览器

Route::get('test', function () {
    // 路由逻辑...
  \Redis::publish('user-channel', json_encode(['username' => 'mary','message'=>'i miss you']));
 });

浏览器访问localhist:/test 执行上面的路由发布消息,会看到窗口中会接受到消息推送

app

一个消息发布/订阅基本实现了,那么问题来了,如何在web端实现消息订阅呢?
官网是这样说滴:编程语言

经过代码调用命令

有时候你可能但愿在 CLI 以外执行 Artisan 命令,好比,你可能但愿在路由或控制器中触发 Artisan 命令,你可使用 Artisan 门面上的call 方法来完成这个功能。call 方法接收被执行的命令名称做为第一个参数,命令参数数组做为第二个参数,退出代码被返回:

那么我这里应该是

Route::get('/get', function () {
    $exitCode = \Artisan::call('redis:subscribe');//这里应该是代码启动进程监听的命令了
});

结果一直超时并不成功!...

 

对于laravel 的消息订阅模式..web端如何完整实现?若是有路过大神玩过,请留下宝贵的笔迹在下参考学习下额

相关文章
相关标签/搜索