1.安装rabbitmq-c
wget -c https://github.com/alanxz/rabbitmq-c/releases/download/v0.8.0/rabbitmq-c-0.8.0.tar.gz tar zxf rabbitmq-c-0.8.0.tar.gz cd rabbitmq-c-0.8.0 ./configure --prefix=/usr/local/rabbitmq-c-0.8.0 make && make install
2.安装amqp(php安装路径需要改下)
wget -c http://pecl.php.net/get/amqp-1.9.3.tgz tar zxf amqp-1.9.3.tgz cd amqp-1.9.3 /usr/local/php/bin/phpize ./configure --with-php-config=/usr/local/php/bin/php-config --with-amqp --with-librabbitmq-dir=/usr/local/rabbitmq-c-0.8.0 make && make install
3.修改php.ini,新加一行
extension = amqp.so
4.重启PHP服务就ok了
5.队列入队代码
<?php //echo phpinfo();die; $conn = [ // Rabbitmq 服务地址 'host' => '127.0.0.1', // Rabbitmq 服务端口 'port' => '5672', // Rabbitmq 帐号 'login' => 'guest', // Rabbitmq 密码 'password' => 'guest', 'vhost'=>'/' ]; //创建连接和channel $conn = new AMQPConnection($conn); var_dump($conn->connect());die; if(!$conn->connect()) { die("Cannot connect to the broker!\n"); } $channel = new AMQPChannel($conn); $exchangeName = 'ex1'; //创建交换机 $ex = new AMQPExchange($channel); $ex->setName($exchangeName); $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型 $ex->setFlags(AMQP_DURABLE); //持久化 //$ex->declare();//老版本已弃用 // 创建队列 $queueName = 'queue1'; $q = new AMQPQueue($channel); $q->setName($queueName); $q->setFlags(AMQP_DURABLE); $q->declareQueue(); // 用于绑定队列和交换机,跟 send.php 中的一致。 $routingKey = 'key_1'; $q->bind($exchangeName, $routingKey); //接收消息 $q->consume(function ($envelope, $queue) { $msg = $envelope->getBody(); echo $msg."\n"; //处理消息 }, AMQP_AUTOACK); $conn->disconnect();
6.消费队列代码
<?php //echo phpinfo();die; $conn = [ // Rabbitmq 服务地址 'host' => '127.0.0.1', // Rabbitmq 服务端口 'port' => '5672', // Rabbitmq 帐号 'login' => 'guest', // Rabbitmq 密码 'password' => 'guest', 'vhost'=>'/' ]; //创建连接和channel $conn = new AMQPConnection($conn); //var_dump($conn);die; if(!$conn->connect()) { die("Cannot connect to the broker!\n"); } $channel = new AMQPChannel($conn); // 用来绑定交换机和队列 $routingKey = 'key_1'; $ex = new AMQPExchange($channel); //var_dump($ex);die; // 交换机名称 $exchangeName = 'ex1'; $ex->setName($exchangeName); // 设置交换机类型 $ex->setType(AMQP_EX_TYPE_DIRECT); // 设置交换机是否持久化消息 $ex->setFlags(AMQP_DURABLE); //$ex->declare();//老版本已弃用 for($i=0; $i<5; ++$i){ echo "Send Message:".$ex->publish(date('H:i:s')."用户".$i."注册" , $routingKey )."\n"; }