我正在使用 Nestjs goleveluprabbitmq 库,想知道是否可以使用 RabbitSubscribe 但一次只消费一条消息?目前,在第一条消息完成处理之前,它会收到多条消息,这会导致更新问题。我已经尝试过使用和不使用队列选项来指定预取计数为 1 的通道。
@RabbitSubscribe({
exchange: 'test_exchange',
routingKey: 'test_update',
queue: 'test_update',
queueOptions: {
channel: 'channel-2',
},
})
public async updateItem(msg) {
await this.service.updateItem(msg);
}
您可以使用标志来指示消息是否正在处理。它可能不是很有效,但应该有效。
import { Nack, RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
class SomeService {
private isProcessing = false;
@RabbitSubscribe({
exchange: 'test_exchange',
routingKey: 'test_update',
queue: 'test_update',
})
public async handleMessage(msg) {
if (this.isProcessing) {
return new Noack(true);
}
this.isProcessing = true;
await this.service.updateItem(msg);
this.isProcessing = false;
return;
}
}
如果
updateItem
由于某种原因失败,消息将被重新处理。