【PHP】浅谈php实现订阅发布模式及redis的实现

订阅发布应用场景:

1、广告推送
2、游戏公告
3、广播--短信、邮件
4、跨应用推送--使用同一个redis实例,net发布publish,php常驻内存订阅subscribe处理业务。

1、浅谈下 设计模式中的 订阅发布模式。

A订阅B,B发布消息通过广播介质,A能获取到消息。

2、发布订阅模式和观察者模式区别和联系:https://zhuanlan.zhihu.com/p/51357583

两个模式最大区别就是 耦合度发布订阅是完全解耦的,观察者模式是低耦合的。

1)发布者与订阅者 通过中介进行联系,随时都可以取消订阅实现解耦,并且对应用完全无影响;

2)观察者模式是通过监听方式,实现对象A对 对象B的观察,B发生改变–A同时会做出更新,具有低耦合度。

3、使用php和laravel5实现的几个发布订阅代码案例,仅供参考: (订阅者必须是常驻内存的deamon守护进程)

1)php原生实现发布订阅:

https://blog.csdn.net/weixin_39774219/article/details/110985179

2)laravel5实现发布订阅:

https://blog.csdn.net/qq_24694139/article/details/107539994

https://blog.csdn.net/guoyanga1/article/details/84822200

php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class Subscribe extends Command
{
    protected $signature = 'sub:msg';

    protected $description = 'redis测试supervisor配置发布订阅';

    protected $time;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
//         #订阅消息redis
//         $redis = new \Redis();
//         $redis->pconnect('101.132.147.66', '6379');
//         $redis->auth('oFFsiuT57mFzYWscjX6f');
        //订阅订单id ORDERID
        Redis::subscribe(['channel1'], function($channel, $message) {
            if (!empty($channel)) {
                #这里$message为10002
                if ($message){
                    //存储到自己的redis库 这里配置了多连接
//                     $redis2 = Redis::connection('driver_outset_time');
//                     $redis2->set('ORDERID_'.$message,time());#value为时间time()
//                     $redis2->EXPIRE('ORDERID_'.$message,time(), 24*60*60);#设置key过期时间为24小时
                    $this->xself($channel, $message);#调用其他方法执行其他业务逻辑
                }
            }
        });
    }
    public function xself($channel, $message)
    {
        //TODO
        echo $channel, $message;
    }

}

4、使用supervisor设置守护进程,前端路由或方法 调用示例:

//redis配置的supervisord发布订阅功能
Route::get('redispublish', function () {
    Redis::publish('channel1', json_encode(['foo' => 'bar']));
});

5、cli输出:

【PHP】浅谈php实现订阅发布模式及redis的实现

Original: https://www.cnblogs.com/xuzhengzong/p/14703740.html
Author: PHP急先锋
Title: 【PHP】浅谈php实现订阅发布模式及redis的实现

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/529014/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球