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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

php自动给文章加关键词链接的函数代码

复制代码 代码如下: <?php $link = array( '百度,http://www.baidu.com/', '服务器软件,http://s.jb51.net/', '【...

10 个经典PHP函数

1. sys_getloadavg() sys_getloadavt()可以获得系 统负载情况。该函数返回一个包含三个元素的数组,每个元素分别代表系统再过去的1、5和15分钟内的平均负...

JSON在PHP中的应用介绍

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。 一、json_encode() 该函数主要用来将数组和对象,转换...

php关联数组与索引数组及其显示方法

数据 username password test 123456 关联数组: mysql_fetch_assoc() array([username]=>'test...

PHP+redis实现微博的拉模型案例详解

本文实例讲述了PHP+redis实现微博的拉模型。分享给大家供大家参考,具体如下: 上回写了一篇推模型的内容,这回分享一篇拉模型的内容。 拉模型 拉模型就是展示微博的时候,获取自己的所有...