PHP基于rabbitmq操作类的生产者和消费者功能示例
作者:爱代码也爱生活 发布时间:2023-11-23 20:03:03
标签:PHP,rabbitmq操作类,生产者,消费者
本文实例讲述了PHP基于rabbitmq操作类的生产者和消费者功能。分享给大家供大家参考,具体如下:
注意事项:
1、accept.php消费者代码需要在命令行执行
2、'username'=>'asdf'
,'password'=>'123456'
改成自己的帐号和密码
RabbitMQCommand.php操作类代码
<?php
/*
* amqp协议操作类,可以访问rabbitMQ
* 需先安装php_amqp扩展
*/
class RabbitMQCommand{
public $configs = array();
//交换机名称
public $exchange_name = '';
//队列名称
public $queue_name = '';
//路由名称
public $route_key = '';
/*
* 持久化,默认True
*/
public $durable = True;
/*
* 自动删除
* exchange is deleted when all queues have finished using it
* queue is deleted when last consumer unsubscribes
*
*/
public $autodelete = False;
/*
* 镜像
* 镜像队列,打开后消息会在节点之间复制,有master和slave的概念
*/
public $mirror = False;
private $_conn = Null;
private $_exchange = Null;
private $_channel = Null;
private $_queue = Null;
/*
* @configs array('host'=>$host,'port'=>5672,'username'=>$username,'password'=>$password,'vhost'=>'/')
*/
public function __construct($configs = array(), $exchange_name = '', $queue_name = '', $route_key = '') {
$this->setConfigs($configs);
$this->exchange_name = $exchange_name;
$this->queue_name = $queue_name;
$this->route_key = $route_key;
}
private function setConfigs($configs) {
if (!is_array($configs)) {
throw new Exception('configs is not array');
}
if (!($configs['host'] && $configs['port'] && $configs['username'] && $configs['password'])) {
throw new Exception('configs is empty');
}
if (empty($configs['vhost'])) {
$configs['vhost'] = '/';
}
$configs['login'] = $configs['username'];
unset($configs['username']);
$this->configs = $configs;
}
/*
* 设置是否持久化,默认为True
*/
public function setDurable($durable) {
$this->durable = $durable;
}
/*
* 设置是否自动删除
*/
public function setAutoDelete($autodelete) {
$this->autodelete = $autodelete;
}
/*
* 设置是否镜像
*/
public function setMirror($mirror) {
$this->mirror = $mirror;
}
/*
* 打开amqp连接
*/
private function open() {
if (!$this->_conn) {
try {
$this->_conn = new AMQPConnection($this->configs);
$this->_conn->connect();
$this->initConnection();
} catch (AMQPConnectionException $ex) {
throw new Exception('cannot connection rabbitmq',500);
}
}
}
/*
* rabbitmq连接不变
* 重置交换机,队列,路由等配置
*/
public function reset($exchange_name, $queue_name, $route_key) {
$this->exchange_name = $exchange_name;
$this->queue_name = $queue_name;
$this->route_key = $route_key;
$this->initConnection();
}
/*
* 初始化rabbit连接的相关配置
*/
private function initConnection() {
if (empty($this->exchange_name) || empty($this->queue_name) || empty($this->route_key)) {
throw new Exception('rabbitmq exchange_name or queue_name or route_key is empty',500);
}
$this->_channel = new AMQPChannel($this->_conn);
$this->_exchange = new AMQPExchange($this->_channel);
$this->_exchange->setName($this->exchange_name);
$this->_exchange->setType(AMQP_EX_TYPE_DIRECT);
if ($this->durable)
$this->_exchange->setFlags(AMQP_DURABLE);
if ($this->autodelete)
$this->_exchange->setFlags(AMQP_AUTODELETE);
$this->_exchange->declare();
$this->_queue = new AMQPQueue($this->_channel);
$this->_queue->setName($this->queue_name);
if ($this->durable)
$this->_queue->setFlags(AMQP_DURABLE);
if ($this->autodelete)
$this->_queue->setFlags(AMQP_AUTODELETE);
if ($this->mirror)
$this->_queue->setArgument('x-ha-policy', 'all');
$this->_queue->declare();
$this->_queue->bind($this->exchange_name, $this->route_key);
}
public function close() {
if ($this->_conn) {
$this->_conn->disconnect();
}
}
public function __sleep() {
$this->close();
return array_keys(get_object_vars($this));
}
public function __destruct() {
$this->close();
}
/*
* 生产者发送消息
*/
public function send($msg) {
$this->open();
if(is_array($msg)){
$msg = json_encode($msg);
}else{
$msg = trim(strval($msg));
}
return $this->_exchange->publish($msg, $this->route_key);
}
/*
* 消费者
* $fun_name = array($classobj,$function) or function name string
* $autoack 是否自动应答
*
* function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
echo $msg."\n"; //处理消息
$queue->ack($envelope->getDeliveryTag());//手动应答
}
*/
public function run($fun_name, $autoack = True){
$this->open();
if (!$fun_name || !$this->_queue) return False;
while(True){
if ($autoack) $this->_queue->consume($fun_name, AMQP_AUTOACK);
else $this->_queue->consume($fun_name);
}
}
}
send.php生产者代码
<?php
set_time_limit(0);
include_once('RabbitMQCommand.php');
$configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);
for($i=0;$i<=100;$i++){
$ra->send(date('Y-m-d H:i:s',time()));
}
exit();
accept.php消费者代码
<?php
error_reporting(0);
include_once('RabbitMQCommand.php');
$configs = array('host'=>'127.0.0.1','port'=>5672,'username'=>'asdf','password'=>'123456','vhost'=>'/');
$exchange_name = 'class-e-1';
$queue_name = 'class-q-1';
$route_key = 'class-r-1';
$ra = new RabbitMQCommand($configs,$exchange_name,$queue_name,$route_key);
class A{
function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
$envelopeID = $envelope->getDeliveryTag();
$pid = posix_getpid();
file_put_contents("log{$pid}.log", $msg.'|'.$envelopeID.''."\r\n",FILE_APPEND);
$queue->ack($envelopeID);
}
}
$a = new A();
$s = $ra->run(array($a,'processMessage'),false);
希望本文所述对大家PHP程序设计有所帮助。
来源:https://blog.csdn.net/nuli888/article/details/51864338


猜你喜欢
- asyncio介绍熟悉c#的同学可能知道,在c#中可以很方便的使用 async 和 await 来实现异步编程,那么在p
- Notepad++ 是一款非常有特色的编辑器,软件小巧高效,支持27种编程语言,通吃C,C++ ,Java ,C#, XML, HTML,
- 最近有Win10系统用户反映,由于自己的电脑安装有两个python软件,所以想要卸载掉其中一个,不过在卸载的时候却发现无法卸载,并且出现提示
- Java 使用Sqllite 数据库如何生成db文件 &n
- 众所周知,pip 可以安装、更新、卸载 Python 的第三方库,非常方便。你们中的许多人可能已经使用 pip
- 前言网上的做法基本都是下面的代码return HttpResponseForbidden()试了一下,效果一般,没有异常页面显示,最终显示的
- Windows 下从源码编译 PaddlePaddle1.环境准备Windows 10 专业版 (64bit)Python 版本 Pytho
- 一丶什么是索引索引是存储引擎快速找到记录的一种数据结构。数据库中的数据可以理解成字典中的单词,而索引就是目录,显而易见这是一种空间换时间的做
- 简介:Mysql数据库按时间点恢复实战对于任何一家企业来讲,数据都是最宝贵的财富。如何保护数据完整性,数据不受损坏,在发生故障时,如何保住数
- Bug如题目所描述。尝试过将按钮的image指向的变量
- 相对于 Ajax,服务端 XMLHTTP 就是在服务端使用 XMLHttpRequest 对象了。虽然说,在服务端使用异步请求是比较不方便的
- SQLPlus是进行Oracle操作的主要前台工具,用户名和密码分别为用户名和密码,连接ORACLE数据库可见,显示的比较混乱,可以通过以下
- 先上个效果图,就是用左右尖括号可改变中间日期的值。(点击中间显示区域有时间选择器弹框,用的插件就不说了,主要说自己原创的部分) &
- 一、字典、元组的多重嵌套例 1:记录全班学生的成绩。分析:定义一个 SimpleGradebook类,学生名是字典self._grades的
- 缘起最近复习设计模式拜读谭勇德的<<设计模式就该这样学>>该书以java语言演绎了常见设计模式本系列笔记拟采用gol
- 1、去除一个数组中的重复元素:使用grep函数代码片段: 代码:my @array = ( 'a', 'b'
- 从某种程度上说,判断一个网页设计师是否优秀,可以从其在WEB开发(或网页设计)中是否合理的采用各种图片格式得出结论。事实上,或许所有人都知道
- 上一篇 我们学习了简单的Python TCP Socket 编程,通过分别写服务端和客户端的代码了解基本的 Python Socket 编程
- xlabel(‘time',‘FontSize',12);如果没有设置位置,默认是在中间在xlabel中也有position
- 问题一:将u'\u810f\u4e71'转换为'\u810f\u4e71'方法:s_unicode = u&