首页 > 解决方案 > 通过 Amqplib 连接到 RabbitMQ 时设置 Heartbeat

问题描述

通过amqplib连接RabbitMQ时,不能设置Heartbeat参数的值。

我这样做:

// NPM Modules
const amqp = require('amqplib/callback_api');
const withAutoRecovery = require('amqplib-auto-recovery');

// Application configuration
const config = settings.getConfig();

withAutoRecovery(amqp, {
  onError: (err) => { console.log(err.message); },
  isErrorUnrecoverable: (err) => { console.log(err) }
}).connect(config.rabbitmq, (err, connection) => {
    // If there are connection errors
    if (err) {
        console.error(this.conn_str_amqp);
        console.error('[AMQP] Connection error:', err.message); 
    } else if (connection) {
        // Connection Error Event
        connection.on('error', (err) => {
            if (err.message !== 'Connection closing') {
                console.error('[AMQP] Closing connection', err.message);
            }
        });
        // Error event when you close the connection
        connection.on('close', () => {
            console.error('[AMQP] Closing connection');
        });
        // Hint to user
        console.log('[AMQP] Connected');
    }
});

这里config.rabbitmq是:

{
  protocol: 'amqp',
  hostname: 'localhost',
  port: 5672,
  username: 'guest',
  password: 'guest',
  locale: 'en_US',
  frameMax: 0x1000,
  heartbeat: 1800,
  vhost: '/',
}

我希望得到Heartbeat = 1800s参数值,在UI 管理窗口中显示默认值Heartbeat = 60s

截屏: 在此处输入图像描述

我尝试以以下格式传递另一个对象而不是config.rabbitmq行(https://www.rabbitmq.com/uri-spec.htmlhttps://www.rabbitmq.com/uri-query-parameters.html ):

function getRabbitMQConnectionString() {
    const rabbitmq = config.rabbitmq;
    return `${rabbitmq.protocol}://${rabbitmq.username}:${rabbitmq.password}@${rabbitmq.hostname}:${rabbitmq.port}${encodeURIComponent(rabbitmq.vhost)}?heartbeat=${rabbitmq.heartbeat}`;
}

因此,结果也与上述效果相似。

请告诉我,如何通过 amqplib 上的 Node.js 客户端应用程序正确设置 Heartbeat 参数?

标签: node.jsrabbitmq

解决方案


出于某种原因,我将心跳设置为 30 秒并且它起作用了。


推荐阅读