1. 程式人生 > >php接收rabbitmq訊息時丟失連線的問題

php接收rabbitmq訊息時丟失連線的問題

php接收rabbitmq訊息時,如果按照下面官方的寫法,可能會導致過幾分鐘後連線就丟失了,接收網頁就像假死一樣:

<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('hello', false, false, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
};
$channel->basic_consume('hello', '', false, true, false, false, $callback);
while (count($channel->callbacks)) {
    $channel->wait();
}
$channel->close();
$connection->close();

最後發現需要在建構函式裡設定連線AMQPStreamConnection的心跳和讀寫超時時間, 超時時間需是心跳的2倍以上,這樣連線就不會消失了

可以在rabbitmq的管理網站上檢視連線的心跳是否設定成功: