Laravel Redis 订阅发布

本文详细介绍了如何使用PHP和Redis实现用户信息更新的场景,包括通过Composer安装Redis扩展,配置缓存和频道,创建Redis服务层,以及生产者和消费者的命令行实现。通过Redis的发布订阅机制,实现实时的用户信息异步更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景:例如:当修改用户信息审核通过后,通过Redis 订阅消息 、生产消息、消费消息、异步的更新用户信息


前提准备:

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
     */
     protected $service;
    public function __construct(RedisService $service)
    {
     	$this->service = $service;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->service->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
     */
     protected $service;
    public function __construct(RedisService $service)
    {
     	$this->service = $service;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->service->subScribe();
        $this->comment('sub successful');
    }
}

将 订阅 消费命令注册在 Kernel

    protected $commands = [
        //
        App\Console\Commands\Redis\PublishCommand::class,
        App\Console\Commands\Redis\SubCommand::class
    ];

项目根目录运行:

1.先订阅消息
	php artisan sub:info 
	
2.后生产消息
	php artisan publish:info 

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值