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的管理网站上查看连接的心跳是否设置成功: