邏輯:
建立鏈接-->建立channel-->建立交換機-->建立隊列-->綁定交換機/隊列/路由鍵-->接收消息
生產者:
$conn_args = array(
'host' => '127.0.0.1',
'port' => '5672',
'login' => 'gedai',
'password' => 'gedai',
'vhost'=>'/credithc'
);
$e_name = 'CREDITHC_CS'; //交換機名
$q_name = 'to_tel_sales'; //無需隊列名
$k_route = 'to_tel_sales'; //路由key
//建立鏈接和channel
$conn = new AMQPConnection($conn_args);
if (!$conn->connect()) {
die("Cannot connect to the broker!\n");
}
$channel = new AMQPChannel($conn);
//消息內容
$message = date("Y-m-d H:i:s") . "TEST send RabbitMQ!";
//建立交換機對象
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
//發送消息
//$channel->startTransaction(); //開始事務
for($i=0; $i<5; ++$i){
echo "Send Message:".$ex->publish($message, $k_route)."\n";
}
//$channel->commitTransaction(); //提交事務
消費者:
//配置信息
$conn_args = array(
'host' => '10.100.13.142',
'port' => '5672',
'login' => 'gedai',
'password' => 'gedai',
'vhost'=>'/credithc'
);
$e_name = 'CREDITHC_CS'; //交換機名
$q_name = 'to_tel_sales'; //隊列名
$k_route = 'to_tel_sales'; //路由key
//建立鏈接和channel
$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); //direct類型
$ex->setFlags(AMQP_DURABLE); //持久化
// echo "Exchange Status:".$ex->declare()."\n";
//建立隊列
$q = new AMQPQueue($channel);
$q->setName($q_name);
$q->setFlags(AMQP_DURABLE); //持久化
echo "Message Total:".$q->declareQueue()."\n";
//綁定交換機與隊列,並指定路由鍵
echo 'Queue Bind: '.$q->bind($e_name, $k_route)."\n";
//阻塞模式接收消息
echo "Message:\n";
while(True){
$q->consume('processMessage');
// $q->consume('processMessage', AMQP_AUTOACK); //自動ACK應答
}
//get獲取
$conn->disconnect();
function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
echo date("Y-m-d H:i:s") . $msg."\n"; //處理消息
$queue->ack($envelope->getDeliveryTag()); //手動發送ACK應答
}
queue對象有兩個方法可用於取消息:consume和get。
前者是阻塞的,無消息時會被掛起,適合循環中使用;
後者則是非阻塞的,取消息時有則取,無則返回false。