Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

5.30. AMQP

5.30.1. 安裝 AMQP

		
yum install -y librabbitmq-devel
pecl install amqp

cat > /srv/php/etc/conf.d/amqp.ini <<EOF
extension=amqp.so
EOF		
		
		

5.30.2. Recv

		
<?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();  
?> 		
		
		

5.30.3. Send

		
<?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();  
?>