如何使用AMQP以“PeekLock”模式从Azure Service Bus队列中获取消息?

时间:2017-04-12 05:54:12

标签: node.js azure amqp azure-servicebus-queues

我们正在尝试在Node应用程序中使用Azure Service Bus。 我们的要求是从队列中获取多条消息

由于Azure SDK for Node不支持批量检索,因此我们决定使用AMQP。虽然我们能够使用Peek Messages获取消息,如此处所述(https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-amqp-request-response#message-operations)。

我们注意到,一旦提取了消息,它们就会从队列中删除。我想知道是否有人了解我们如何使用AMQP和Node在“PeekLock”模式下获取消息。对于AMQP,我们使用的是amqp10节点包(https://www.npmjs.com/package/amqp10)。

以下是我们查看邮件的代码:

const AMQPClient = require('amqp10/lib').Client,
Policy = require('amqp10/lib').Policy;

const protocol = 'amqps';
const keyName = 'RootManageSharedAccessKey';
const sasKey = 'My Shared Access Key'
const serviceBusHost = 'account-name.servicebus.windows.net';
const uri = protocol + '://' + encodeURIComponent(keyName) + ':' + encodeURIComponent(sasKey) + '@' + serviceBusHost;
const queueName = 'test1';
var client = new AMQPClient(Policy.ServiceBusQueue);
client.connect(uri)
.then(function () {
    return Promise.all([
        client.createReceiver(queueName),
        client.createSender(queueName)
    ]);
})
.spread(function(receiver, sender) {
    console.log(receiver);
    console.log(sender);
    console.log('--------------------------------------------------------------------------');
    receiver.on('errorReceived', function(err) {
        // check for errors
        console.log(err);
    });
    receiver.on('message', function(message) {
        console.log('Received message');
        console.log(message);
        console.log('------------------------------------');
    });

    return sender.send([], {
        operation: 'com.microsoft:peek-message',
        'message-count': 5
    });
})
.error(function (e) {
    console.warn('connection error: ', e);
});

1 个答案:

答案 0 :(得分:1)

By default receiver works in auto-settle mode, you have to change it to settle on disposition:

const { Constants } = require('amqp10')

// 
// ...create client, connect, etc...
//

// Second parameter of createReceiver method enables overwriting policy parameters
const receiver = client.createReceiver(queueName, {
  attach: {
    rcvSettleMode: Constants.receiverSettleMode.settleOnDisposition
  }
})

Do not forget to accept/reject/release a message after processing it:

receiver.on('message', msg => {
  //
  // ...do something smart with a message...
  //

  receiver.accept(msg) // <- manually settle a message
})