PHP中使用AMQP消息队列

入队列:


//连接RabbitMQ
$conn_args = array( 'host'=>'localhost' , 'port'=> '5672', 'login'=>'guest' , 

'password'=> 'guest','vhost' =>'/');
$conn = new AMQPConnection($conn_args);
$conn->connect();
//创建exchange名称和类型
$channel = new AMQPChannel($conn);
$ex = new AMQPExchange($channel);
$ex->setName('direct_exchange_name');
$ex->setType(AMQP_EX_TYPE_DIRECT);
$ex->setFlags(AMQP_DURABLE | AMQP_AUTODELETE);
$ex->declare();
//创建queue名称,使用exchange,绑定routingkey
$q = new AMQPQueue($channel);
$q->setName('queue_name');
$q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE);
$q->declare();
$q->bind('direct_exchange_name', 'routingkey_name');
//消息发布
$channel->startTransaction();
$message = json_encode(array('Hello World!','DIRECT'));

//delivery_mode 为2表示持久化,1非持久化
$ex->publish($message, 'routingkey_name',AMQP_NOPARAM,array('delivery_mode'=>2,'priority'=>9));
$channel->commitTransaction();
$conn->disconnect();
?>


取队列:


//连接RabbitMQ
$conn_args = array( 'host'=>'localhost' , 'port'=> '5672', 'login'=>'guest' , 'password'=> 'guest','vhost' =>'/');
$conn = new AMQPConnection($conn_args);
$conn->connect();
//设置queue名称,使用exchange,绑定routingkey
$channel = new AMQPChannel($conn);
$q = new AMQPQueue($channel);
$q->setName('queue_name');
$q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE);
$q->declare();
$q->bind('direct_exchange_name', 'routingkey_name');   
//消息获取
$messages = $q->get(AMQP_AUTOACK) ;
if ($messages){
      var_dump(json_d ecode($messages->getBody(), true ));
}
$conn->disconnect();
?>

你可能感兴趣的:(LNMP)