Redis 发布/订阅示例

2020-01-02  本文已影响0人  马蹄哒

环境:Laravel 6 + Homestesd

订阅

具体操作:

  1. 创建artisan命令
php artisan make:command RedisSubscribe 
#生成的文件位于App\Console\Commands
  1. 将文件修改如下
<?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::subscribe(['test-channel'], function ($message) {
            echo $message;
        });
    }
}
  1. 运行artisan命令
vagrant ssh
cd ~/PATH-TO-YOUR-CODE  #切换到项目根目录执行
php artisan redis:subscribe #执行此命令后不会有输出,将一直等待数据发布

发布

具体操作:

  1. 修改路由web.php
Route::get('publish', function () {
    return \Illuminate\Support\Facades\Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});
  1. 浏览器访问:http://YOUR-DOMAIN/publish,页面显示的数字表示订阅此频道的客户端数量;大于0表示发布成功,然后可以到artisan命令查看结果如下:

提示:Homestead需要安装phpredis扩展

参考:
https://laravel.com/docs/6.x/redis#pubsub

上一篇 下一篇

猜你喜欢

热点阅读