环境:Laravel 6 + Homestesd
订阅
- 使用artisan命令保持监听
具体操作:
- 创建artisan命令
php artisan make:command RedisSubscribe
#生成的文件位于App\Console\Commands
- 将文件修改如下
<?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;
});
}
}
- 运行artisan命令
vagrant ssh
cd ~/PATH-TO-YOUR-CODE #切换到项目根目录执行
php artisan redis:subscribe #执行此命令后不会有输出,将一直等待数据发布
发布
- 根据请求数据发布
具体操作:
- 修改路由web.php
Route::get('publish', function () {
return \Illuminate\Support\Facades\Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});
- 浏览器访问:http://YOUR-DOMAIN/publish,页面显示的数字表示订阅此频道的客户端数量;大于0表示发布成功,然后可以到artisan命令查看结果如下:
提示:Homestead需要安装phpredis扩展
网友评论