我有一个PHP脚本的消费者工作者。
但有时RabbitMQ服务器停止运行,
我收到此错误:
PHP Fatal error: Uncaught exception 'ErrorException' with message 'fwrite(): send of 19 bytes failed with errno=32 Broken pipe' in /home/user/pusher/rabbitmq-worker/vendor/php-amqplib/php-amqplib/PhpAmqpLib/Wire/IO/StreamIO.php:281
我希望能够使用try / catch块处理此错误,以便向我的控制台抛出一个错误的错误,或者尝试在一段时间后重新连接。
这是我到目前为止的代码:
while (true) {
try {
$connection = new AMQPStreamConnection(RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_USER, RABBITMQ_PASS);
$channel = $connection->channel();
$channel->queue_declare(RABBITMQ_DT_QUEUE, false, true, false, false);
$channel->basic_qos(null, 11, null);
echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
$callback = function($req) {
sleep(3);//Some task that takes 3 sec
};
$channel->basic_consume(RABBITMQ_QUEUE, '', false, false, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
} catch (Exception $e) {
sleep(1);
}
缺少什么?
答案 0 :(得分:4)
在连接上定义下一个参数
keepalive: true
heartbeat: 15 // An example
这是AMQPStreamConnection::__constructor()
注意: 如果您连接到某个远程服务器,我建议设置高达超时
connection_timeout: 10
read_write_timeout: 30
UPD:
您可以捕获ErrorException
并尝试再次连接到服务器