侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP高级编程之消息队列原理与实现方法详解

php  /  管理员 发布于 7年前   159

本文实例讲述了PHP高级编程之消息队列原理与实现方法。分享给大家供大家参考,具体如下:

1. 什么是消息队列

消息队列(英语:Message queue)是一种进程间通信或同一进程的不同线程间的通信方式

2. 为什么使用消息队列

消息队列技术是分布式应用间交换信息的一种技术。消息队列可驻留在内存或磁盘上,队列存储消息直到它们被应用程序读出。通过消息队列,应用程序可独立地执行,它们不需要知道彼此的位置、或在继续执行前不需要等待接收程序接收此消息。

3. 什么场合使用消息队列

你首先需要弄清楚,消息队列与远程过程调用的区别,在很多读者咨询我的时候,我发现他们需要的是RPC(远程过程调用),而不是消息队列。

消息队列有同步或异步实现方式,通常我们采用异步方式使用消息队列,远程过程调用多采用同步方式。

MQ与RPC有什么不同? MQ通常传递无规则协议,这个协议由用户定义并且实现存储转发;而RPC通常是专用协议,调用过程返回结果。

4. 什么时候使用消息队列

同步需求,远程过程调用(PRC)更适合你。

异步需求,消息队列更适合你。

目前很多消息队列软件同时支持RPC功能,很多RPC系统也能异步调用。

消息队列用来实现下列需求

① 存储转发

② 分布式事务

③ 发布订阅

④ 基于内容的路由

⑤ 点对点连接

5. 谁负责处理消息队列

通常的做法,如果小的项目团队可以有一个人实现,包括消息的推送,接收处理。如果大型团队,通常是定义好消息协议,然后各自开发各自的部分,例如一个团队负责写推送协议部分,另一个团队负责写接收与处理部分。

那么为什么我们不讲消息队列框架化呢?

框架化有几个好处:

① 开发者不用学习消息队列接口
② 开发者不需要关心消息推送与接收
③ 开发者通过统一的API推送消息
④ 开发者的重点是实现业务逻辑功能

6. 怎么实现消息队列框架

下面是作者开发的一个SOA框架,该框架提供了三种接口,分别是SOAP,RESTful,AMQP(RabbitMQ),理解了该框架思想,你很容易进一步扩展,例如增加XML-RPC, ZeroMQ等等支持。

https://github.com/netkiller/SOA

本文只讲消息队列框架部分。

6.1. 守护进程

消息队列框架是本地应用程序(命令行程序),我们为了让他在后台运行,需要实现守护进程。

https://github.com/netkiller/SOA/blob/master/bin/rabbitmq.php

每个实例处理一组队列,实例化需要提供三个参数,$queueName = '队列名', $exchangeName = '交换名', $routeKey = '路由'

$daemon = new \framework\RabbitDaemon($queueName = 'email', $exchangeName = 'email', $routeKey = 'email');

守护进程需要使用root用户运行,运行后会切换到普通用户,同时创建进程ID文件,以便进程停止的时候使用。

守护进程核心代码https://github.com/netkiller/SOA/blob/master/system/rabbitdaemon.class.php

6.2. 消息队列协议

消息协议是一个数组,将数组序列化或者转为JSON推送到消息队列服务器,这里使用json格式的协议。

$msg = array(    'Namespace'=>'namespace',    "Class"=>"Email",    "Method"=>"smtp",    "Param" => array(        $mail, $subject, $message, null    ));

序列化后的协议

{"Namespace":"single","Class":"Email","Method":"smtp","Param":["[email protected]","Hello"," TestHelloWorld",null]}

使用json格式是考虑到通用性,这样推送端可以使用任何语言。如果不考虑兼容,建议使用二进制序列化,例如msgpack效率更好。

6.3. 消息队列处理

消息队列处理核心代码

https://github.com/netkiller/SOA/blob/master/system/rabbitmq.class.php

所以消息的处理在下面一段代码中进行

$this->queue->consume(function($envelope, $queue) {    $speed = microtime(true);    $msg = $envelope->getBody();    $result = $this->loader($msg);    $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答    //$this->logging->info(''.$msg.' '.$result)    $this->logging->debug('Protocol: '.$msg.' ');    $this->logging->debug('Result: '. $result.' ');    $this->logging->debug('Time: '. (microtime(true) - $speed) .'');});

public function loader($msg = null) 负责拆解协议,然后载入对应的类文件,传递参数,运行方法,反馈结果。

Time 可以输出程序运行所花费的时间,对于后期优化十分有用。

提示

loader() 可以进一步优化,使用多线程每次调用loader将任务提交到线程池中,这样便可以多线程处理消息队列。

6.4. 测试

测试代码 https://github.com/netkiller/SOA/blob/master/test/queue/email.php

 '192.168.4.1',    'port' => '5672',    'vhost' => '/',    'login' => 'guest',    'password' => 'guest'    ));$connection->connect() or die("Cannot connect to the broker!\n");$channel = new AMQPChannel($connection);$exchange = new AMQPExchange($channel);$exchange->setName($exchangeName);$queue = new AMQPQueue($channel);$queue->setName($queueName);$queue->setFlags(AMQP_DURABLE);$queue->declareQueue();$msg = array(    'Namespace'=>'namespace',    "Class"=>"Email",    "Method"=>"smtp",    "Param" => array(        $mail, $subject, $message, null    ));$exchange->publish(json_encode($msg), $routeKey);printf("[x] Sent %s \r\n", json_encode($msg));$connection->disconnect();

这里只给出了少量测试与演示程序,如有疑问请到渎者群,或者公众号询问。

7. 多线程

上面消息队列 核心代码如下

$this->queue->consume(function($envelope, $queue) {    $msg = $envelope->getBody();    $result = $this->loader($msg);    $queue->ack($envelope->getDeliveryTag());});

这段代码生产环境使用了半年,发现效率比较低。有些业务场入队非常快,但处理起来所花的时间就比较长,容易出现队列堆积现象。

增加多线程可能更有效利用硬件资源,提高业务处理能力。代码如下

classspath = __DIR__.'/../queue';        $this->msg = $msg;        $this->logging = $logging;        $this->queue = $queue;    }    public function run() {        $speed = microtime(true);        $result = $this->loader($this->msg);        $this->logging->debug('Result: '. $result.' ');        $this->logging->debug('Time: '. (microtime(true) - $speed) .'');    }    // private    public function loader($msg = null){        $protocol     = json_decode($msg,true);        $namespace    = $protocol['Namespace'];        $class         = $protocol['Class'];        $method     = $protocol['Method'];        $param         = $protocol['Param'];        $result     = null;        $classspath = $this->classspath.'/'.$this->queue.'/'.$namespace.'/'.strtolower($class) . '.class.php';        if( is_file($classspath) ){require_once($classspath);//$class = ucfirst(substr($request_uri, strrpos($request_uri, '/')+1));if (class_exists($class)) {    if(method_exists($class, $method)){        $obj = new $class;        if (!$param){$tmp = $obj->$method();$result = json_encode($tmp);$this->logging->info($class.'->'.$method.'()');        }else{$tmp = call_user_func_array(array($obj, $method), $param);$result = (json_encode($tmp));$this->logging->info($class.'->'.$method.'("'.implode('","', $param).'")');        }    }else{        $this->logging->error('Object '. $class. '->' . $method. ' is not exist.');    }}else{    $msg = sprintf("Object is not exist. (%s)", $class);    $this->logging->error($msg);}        }else{$msg = sprintf("Cannot loading interface! (%s)", $classspath);$this->logging->error($msg);        }        return $result;    }}class RabbitMQ {    const loop = 10;    protected $queue;    protected $pool;    public function __construct($queueName = '', $exchangeName = '', $routeKey = '') {        $this->config = new \framework\Config('rabbitmq.ini');        $this->logfile = __DIR__.'/../log/rabbitmq.%s.log';        $this->logqueue = __DIR__.'/../log/queue.%s.log';        $this->logging = new \framework\log\Logging($this->logfile, $debug=true); //.H:i:s        $this->queueName    = $queueName;        $this->exchangeName    = $exchangeName;        $this->routeKey        = $routeKey;        $this->pool = new \Pool($this->config->get('pool')['thread']);    }    public function main(){        $connection = new \AMQPConnection($this->config->get('rabbitmq'));        try {$connection->connect();if (!$connection->isConnected()) {    $this->logging->exception("Cannot connect to the broker!".PHP_EOL);}$this->channel = new \AMQPChannel($connection);$this->exchange = new \AMQPExchange($this->channel);$this->exchange->setName($this->exchangeName);$this->exchange->setType(AMQP_EX_TYPE_DIRECT); //direct类型$this->exchange->setFlags(AMQP_DURABLE); //持久�?$this->exchange->declareExchange();$this->queue = new \AMQPQueue($this->channel);$this->queue->setName($this->queueName);$this->queue->setFlags(AMQP_DURABLE); //持久�?$this->queue->declareQueue();$this->queue->bind($this->exchangeName, $this->routeKey);$this->queue->consume(function($envelope, $queue) {    $msg = $envelope->getBody();    $this->logging->debug('Protocol: '.$msg.' ');    //$result = $this->loader($msg);    $this->pool->submit(new RabbitThread($this->queueName,new \framework\log\Logging($this->logqueue, $debug=true), $msg));    $queue->ack($envelope->getDeliveryTag());});$this->channel->qos(0,1);        }        catch(\AMQPConnectionException $e){$this->logging->exception($e->__toString());        }        catch(\Exception $e){$this->logging->exception($e->__toString());$connection->disconnect();$this->pool->shutdown();        }    }    private function fault($tag, $msg){        $this->logging->exception($msg);        throw new \Exception($tag.': '.$msg);    }    public function __destruct() {    }}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:

  • php实现通过stomp协议连接ActiveMQ操作示例
  • php ActiveMQ的安装与使用方法图文教程
  • PHP使用ActiveMQ实现消息队列的方法详解
  • PHP使用ActiveMQ实例
  • PHP Beanstalkd消息队列的安装与使用方法实例详解
  • php+redis实现消息队列功能示例
  • PHP+RabbitMQ实现消息队列的完整代码
  • 使用PHP访问RabbitMQ消息队列的方法示例
  • php实现websocket实时消息推送
  • php 使用ActiveMQ发送消息,与处理消息操作示例


  • 上一条:
    正版phpstorm免费激活步骤教程详解
    下一条:
    PHP变量作用域(全局变量&局部变量)&global&static关键字用法实例分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客