const amqp = require('amqplib');
async function consumeMessages() {
try {
// 1. 连接 RabbitMQ
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
// 2. 声明队列(如果不存在则创建)
const queue = 'jaymin.delay.queue';
await channel.assertQueue(queue, {
durable: false // 是否持久化
});
console.log('等待消息中...');
// 3. 消费消息
channel.consume(queue, (msg) => {
if (msg !== null) {
const content = msg.content.toString();
console.log('收到消息:', content);
// 处理消息内容
try {
const data = JSON.parse(content);
console.log('解析后的数据:', data);
} catch (e) {
console.log('原始文本:', content);
}
// 4. 确认消息已处理
channel.ack(msg);
}
}, {
noAck: false // 设置为 false 表示需要手动确认
});
// 处理连接关闭
process.on('SIGINT', async () => {
await channel.close();
await connection.close();
console.log('连接已关闭');
process.exit(0);
});
} catch (error) {
console.error('错误:', error);
}
}
consumeMessages();