先查看是否已经安装此扩展:
php -m |grep amqp 如果没有那么安装amqp扩展
官方安装说明:http://www.php.net/manual/zh/amqp.installation.php
下载rabbitmq-c的v0.2版:https://github.com/alanxz/rabbitmq-c/tags
或者:
wget https://github.com/alanxz/rabbitmq-c/tarball/0.2 tar zxvf 0.2 cd alanxz-rabbitmq*
下载最新版的codegen配件:https://github.com/rabbitmq/rabbitmq-codegen/downloads
wget https://github.com/rabbitmq/rabbitmq-codegen/tarball/master tar zxvf master mv rabbitmq-* codegen autoreconf -i ./configure && make && make install
扩展编译:
wget http://pecl.php.net/get/amqp-1.0.0.tgz tar zxvf amqp-1.0.0.tgz cd amqp-1.0.0 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/bin/php-config --with-amqp #你自己phpconfig路径 make && make install
如果OK 在php.ini中添加: extension = amqp.so
php -m |grep amqp 如出现 amqp 扩展,安装完毕
发脚本:
'192.168.0.12', 'port' => '5672', 'login' => 'guest', 'password' => 'guest', 'vhost'=>'/' ); $e_name = "exchange"; $q_name = "queue"; $k_route = "route.key"; $conn = new AMQPConnection($conn_args); if ($conn->connect()) { echo "Established a connection to the broker \n"; } else { echo "Cannot connect to the broker \n "; } //你的消息 $message = "hello word ! ".time(); //创建channel $channel = new AMQPChannel($conn); //创建exchange $ex = new AMQPExchange($channel); $ex->setName($e_name);//创建名字 $ex->setType(AMQP_EX_TYPE_DIRECT); $ex->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); echo "exchange status:".$ex->declare(); echo "\n"; //创建队列 $q = new AMQPQueue($channel); //设置队列名字 如果不存在则添加 $q->setName($q_name); $q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); //echo "queue status: ".$q->declare(); echo "\n"; echo 'queue bind: '.$q->bind($e_name, $k_route);//将你的队列绑定到routingKey echo "\n"; $channel->startTransaction(); //for($i=0; $i<500; ++$i){} echo "send: ".$ex->publish($message, $k_route); //将你的消息通过制定routingKey发送 echo "\n"; $channel->commitTransaction(); $conn->disconnect();
收消息:
'192.168.0.12', 'port' => '5672', 'login' => 'guest', 'password' => 'guest', 'vhost'=>'/' ); $e_name = "exchange"; $q_name = "queue"; $k_route = "route.key"; $conn = new AMQPConnection($conn_args); if (!$conn->connect()) { die("Cannot connect to the broker!\n"); } $channel = new AMQPChannel($conn); $ex = new AMQPExchange($channel); $ex->setName($e_name); $ex->setType(AMQP_EX_TYPE_DIRECT); $ex->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); echo "Exchange Status:".$ex->declare()."\n"; $q = new AMQPQueue($channel); $q->setName($q_name); $q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); //echo "Message Total:".$q->declare()."\n"; echo 'Queue Bind: '.$q->bind($e_name, $k_route)."\n"; echo "Message:\n"; while(True){ $q->consume('processMessage'); //$q->consume('processMessage', AMQP_AUTOACK); } $conn->disconnect(); function processMessage($envelope, $queue) { $msg = $envelope->getBody(); echo $msg."\n"; $queue->ack($envelope->getDeliveryTag()); }