场景:当生产者 产生一个用户id,消费者获取到用户id 取更改用户状态;
前提准备:
1. composer require predis/predis
2. env 文件 更新 CACHE_DRIVER = redis
3. env 文件 新增 REdis_CHANNEL = edit_user_channel
4. 新增 config/common.PHP 并写入以下内容 后 并执行: PHP artisan config:cache
return [
'edit_user_channel' => [
env('REdis_CHANNEL', 'edit_user_channel')
],
];
创建 redis 服务层(RedisService) 并写入以下代码
<?PHP
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
/**
* copyright (C), 2021-2021, old_liu_cms.
* FileName: ${FILE_NAME}
* Description: 说明
*
* @author lwl
* @Create Date 2021/11/8 11:04
* @Update Date 2021/11/8 11:04 By lwl
* @version v1.0
*/
class RedisService
{
/**
* FunctionName:publish
* Description:生产者发布
* Author:lwl
*/
public function publish()
{
$editUserChannel = config('common.edit_user_channel.0');
$userId = 1;
try {
$data = ['user_id' => $userId];
Redis::publish($editUserChannel, json_encode($data));
} catch (\Exception $exception) {
echo $exception->getMessage();
}
}
/**
* FunctionName:subScribe
* Description:消费者订阅
* Author:lwl
*/
public function subScribe()
{
set_time_limit(0);
ini_set('default_socket_timeout', -1);
try {
$channels = config('common.edit_user_channel');
echo 'start' . "\n";
Redis::subscribe($channels, function ($json, $message) {
$data = json_decode($json, 1);
User::edit($data['user_id'], ['sex' => 1]);
});
} catch (\Exception $e) {
echo $e->getMessage();
}
}
}
通过命令生成生产者:
PHP artisan make:command Redis/PublishCommand;
生产者内容:
<?PHP
namespace App\Console\Commands\Redis;
use App\Services\RedisService;
use Illuminate\Console\Command;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'publish:info';//这个命令根据自己喜欢而定
/**
* 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 = new RedisService();
$redis->publish();
$this->comment('publish successful');
}
}
消费者内容:
<?PHP
namespace App\Console\Commands\Redis;
use App\Services\RedisService;
use Illuminate\Console\Command;
class SubCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sub:info';
/**
* 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 = new RedisService();
$redis->subScribe();
$this->comment('sub successful');
}
}
项目根目录运行:
1.先订阅消息
PHP artisan sub:info
2.后生产消息
PHP artisan publish:info
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。