使用PHP访问RabbitMQ消息队列的方法示例

yipeiwu_com5年前PHP代码库

本文实例讲述了使用PHP访问RabbitMQ消息队列的方法。分享给大家供大家参考,具体如下:

扩展安装

PHP访问RabbitMQ实际使用的是AMQP协议,所以我们只要安装epel库中的php-pecl-amqp这个包即可

rpm -ivh http://mirror.neu.edu.cn/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install php-pecl-amqp

交换建立

<?php
$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange1');
$exchange->setType('fanout');
$exchange->declare();

队列建立

<?php
$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare();

队列绑定

<?php
$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare();
$queue->bind('exchange1', 'routekey');

消息发送

<?php
$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName('exchange5');
$exchange->setType('fanout');
$exchange->declare();
for($i = 0; $i < 2000000; $i++) {
 $exchange->publish("message $i", "routekey");
}

消息接收

<?php
$connection = new AMQPConnection();
$connection->connect();
$channel = new AMQPChannel($connection);
$queue = new AMQPQueue($channel);
$queue->setName('queue1');
$queue->declare();
$queue->bind('exchange1', 'routekey');
while (true) {
  $queue->consume(function($envelope, $queue){
   echo $envelope->getBody(), PHP_EOL;
  }, AMQP_AUTOACK);
}

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

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

相关文章

让Json更懂中文(JSON_UNESCAPED_UNICODE)

复制代码 代码如下: <?php echo json_encode("中文"); //"\u4e2d\u6587" 这就让我们这些在天朝做开发的同学, 很是头疼, 有的时候还不得...

PHP实现数组转JSon和JSon转数组的方法示例

本文实例讲述了PHP实现数组转JSon和JSon转数组的方法。分享给大家供大家参考,具体如下: 数组转JSon数据: $array_1 = array(); //一维数组 $arra...

PHP快速排序算法实现的原理及代码详解

PHP快速排序算法实现的原理及代码详解

算法原理 下列动图来自五分钟学算法,演示了快速排序算法的原理和步骤。 步骤: 从数组中选个基准值 将数组中大于基准值的放同一边、小于基准值的放另一边,基准值位于中间位置 递归的对分...

php mail to 配置详解

复制代码 代码如下: [mail function] ; For Win32 only. SMTP = mail3.focuschina.com smtp_port = 25 ; For...

php 修改上传文件大小限制实例详解

1. 修改 max_execution_time 在php中,默认的页面最久执行时间为 30 秒,超过30秒,该脚本就停止执行. 这样就会出现无法打开网页的情况.这时我们可以修改 max...