Redis 广播和发布
redis的广播和发布
第一步使用 php artisan make:command RedisSubscribe
创建RedisSubscribe文件
<?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 = 'Redis 发布订阅';
/**
* 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;
});
}
}
第二步注册命令
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
\App\Console\Commands\RedisSubscribe::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
第三步 创建控制器
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
class NewController extends Controller
{
public function handleRedis(Request $request)
{
Redis::publish('test-channel', 'hello word');
}
}
第四步访问控制器,但是不能收到广播
Commands 目录下不用手动注册吧 :see_no_evil:
@lddtime 不手动注册的话kernel文件中没有
@PHP_LHF 那
$this->load(__DIR__.'/Commands');
起什么作用呢@lddtime 加载Commands下的文件吧