laravel使用redis订阅/发布

3 篇文章 1 订阅
  • 背景
近来不是特别忙,将一些常用的需要用到的总结一下。今天主要写的是:使用redis做订阅/发布
  • 代码-主要逻辑模块
<?php
/**
 * 主要逻辑模块
 * Created by PhpStorm.
 * User: Moer
 * Date: 2019/12/26
 * Time: 11:08
 */

namespace App\Services\Redis;


use App\Services\ComService;
use Illuminate\Support\Facades\Redis;

class RedisService extends ComService
{

    /**
     * 消费者订阅
     */
    public function subScribe()
    {
        //设置php脚本执行时间
        set_time_limit(0);
        //设置socket连接超时时间
        ini_set('default_socket_timeout', -1);
        try{
            // 必须入生产者频道相对应
            $channels = ['testRedisPubSub','testRedisPubSub2']//可以监听多个频道,根据自己喜欢而定
            echo 'start'."\n";
            
            Redis::subscribe($channels, function ($channel,$message){
                echo "channel:".$channel.",message:".$message."\n";
            });


        }catch (\Exception $e){
            echo $e->getMessage();
        }
    }

    /**
     * 生产者发布
     */
    public function publish()
    {
        $channelName = "testRedisPubSub";//频道
        $channelName2 = "testRedisPubSub2";//频道2
        //向指定频道发送消息
        try {
            //可以多个频道,根据自己喜欢而定
            for ($i=0;$i<5;$i++){
                $data = array('key' => 'key'.$i, 'data' => 'testdata'.date('Y-m-d H:i:s'));
                $ret =Redis::publish($channelName, json_encode($data));
                print_r($ret . "\n");
            }
            for ($i=0;$i<5;$i++){
                $data = array('key' => 'key'.$i, 'data' => 'testdata_two'.date('Y-m-d H:i:s'));
                //发布消息 
                /*消息格式是字符串格式,第一个参数为频道名,第二个参数是发布的消息内容*/
                $ret =Redis::publish($channelName2, json_encode($data));
                print_r($ret . "\n");
            }
        } catch (\Exception $e){
            echo $e->getMessage();
        }
    }
}
  • 代码-命令模块

如果你使用的是laravel框架,可以直接命令生成命令文件: php artisan make:command Redis/PublishCommand 和php artisan make:command Redis/SubCommand.
执行完后,就会生成如下两个文件。
再执行  php artisan publish:info 或  php artisan sub:info 
  • 1、生产者发布命令模块
<?php
/**
 * 生产者发布命令
 * Created by PhpStorm.
 * User: Moer
 * Date: 2019/12/26
 * Time: 11:08
 */
namespace App\Console\Commands\Redis;

use App\Services\Redis\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');
    }
}

  • 2、消费者订阅命令模块
<?php
/**
 * 消费者订阅命令
 * Created by PhpStorm.
 * User: Moer
 * Date: 2019/12/26
 * Time: 11:08
 */
namespace App\Console\Commands\Redis;

use App\Services\Redis\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');
    }
}

  • 3、加载命令文件
<?php

namespace App\Console;

use App\Console\Commands\Redis\PublicCommand;
use App\Console\Commands\Redis\SubCommand;
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 = [
        PublicCommand::class,//生产者发布加载
        SubCommand::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');
        \App\Console\Commands\WorkerManCommand::class;

        require base_path('routes/console.php');
    }
}

  • 命令
注意:命令执行的先后顺序,先执行消费者订阅,再执行生成者发布。
  • 执行 php artisan sub:info
$ php artisan sub:info
Cannot load Xdebug - it was already loaded
start

  • 执行 php artisan publish:info
$ php artisan publish:info
Cannot load Xdebug - it was already loaded
1
1
1
1
1
1
1
1
1
1
publish successful
  • 结果
$ php artisan sub:info
Cannot load Xdebug - it was already loaded
start
channel:{"key":"key0","data":"testdata2019-12-26 08:40:32"},message:testRedisPubSub
channel:{"key":"key1","data":"testdata2019-12-26 08:40:32"},message:testRedisPubSub
channel:{"key":"key2","data":"testdata2019-12-26 08:40:32"},message:testRedisPubSub
channel:{"key":"key3","data":"testdata2019-12-26 08:40:32"},message:testRedisPubSub
channel:{"key":"key4","data":"testdata2019-12-26 08:40:32"},message:testRedisPubSub
channel:{"key":"key0","data":"testdata_two2019-12-26 08:40:32"},message:testRedisPubSub2
channel:{"key":"key1","data":"testdata_two2019-12-26 08:40:32"},message:testRedisPubSub2
channel:{"key":"key2","data":"testdata_two2019-12-26 08:40:32"},message:testRedisPubSub2
channel:{"key":"key3","data":"testdata_two2019-12-26 08:40:32"},message:testRedisPubSub2
channel:{"key":"key4","data":"testdata_two2019-12-26 08:40:32"},message:testRedisPubSub2
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值