美文网首页
Redis 发布/订阅示例

Redis 发布/订阅示例

作者: 马蹄哒 | 来源:发表于2020-01-02 16:00 被阅读0次

环境:Laravel 6 + Homestesd

订阅

  • 使用artisan命令保持监听

具体操作:

  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

相关文章

网友评论

      本文标题:Redis 发布/订阅示例

      本文链接:https://www.haomeiwen.com/subject/yupmoctx.html