yum install -y librabbitmq-devel pecl install amqp cat > /srv/php/etc/conf.d/amqp.ini <<EOF extension=amqp.so EOF
<?php $credentials = array( 'host'=>'localhost' , 'port'=> '5672', 'login'=>'guest' , 'password'=> 'guest','vhost' =>'/'); $conn = new AMQPConnection($credentials); $conn->connect(); $channel = new AMQPChannel($conn); //設置queue名稱,使用exchange名稱,綁定routing_key $queue = new AMQPQueue($channel); $queue->setName('queue_name'); $queue->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); $queue->declare(); $queue->bind('exchange_name', 'routing_key'); //消息獲取 $messages = $queue->get(AMQP_AUTOACK) ; if ($messages){ var_dump(json_decode($messages->getBody(), true )); } $conn->disconnect(); ?>
<?php //連接RabbitMQ $credentials = array( 'host'=>'localhost' , 'port'=> '5672', 'login'=>'guest', 'password'=> 'guest','vhost' =>'/'); $conn = new AMQPConnection($credentials); $conn->connect(); //創建exchange名稱和類型 $channel = new AMQPChannel($conn); $exchange = new AMQPExchange($channel); $exchange->setName('exchange_name'); $exchange->setType(AMQP_EX_TYPE_DIRECT); $exchange->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); $exchange->declare(); //創建queue名稱,使用exchange,綁定routing_key $queue = new AMQPQueue($channel); $queue->setName('queue_name'); $queue->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); $queue->declare(); $queue->bind('exchange_name', 'routing_key'); //消息發佈 $channel->startTransaction(); $message = json_encode(array('Hello World!','DIRECT')); $exchange->publish($message, 'routing_key'); $channel->commitTransaction(); $conn->disconnect(); ?>