在Node.js中实现消费rabbitmq队列消息示例
前端  /  管理员 发布于 11个月前   294
在Node.js中实现消费rabbitmq队列消息功能。
示例代码:
index.js
var amqp = require('amqplib/callback_api');
const MyConsume = require('./MyConsume');
amqp.connect('amqp://name:password!@localhost:5672/vhost', function (error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function (error1, channel) {
if (error1) {
throw error1;
}
var exchangeName = 'my_topic'; // 你的 exchange 名称
var exchangeType = 'topic'; // exchange 类型,可以是 direct、fanout、topic 等
var routingKey = 'my_routing_key'; // 你的 routing key
var queueName = 'my_queue'; // 你的队列名称
channel.assertExchange(exchangeName, exchangeType, { durable: true }, function(error2, ok) {
if (error2) {
throw error2;
}
console.log('Exchange ' + exchangeName + ' is ready');
// 声明一个队列
channel.assertQueue(queueName, { durable: true }, function(error3, q) {
if (error3) {
throw error3;
}
console.log('Queue ' +queueName + ' is created');
// 将队列绑定到 exchange,并指定 routing key
channel.bindQueue(queueName, exchangeName, routingKey);
console.log('Queue ' + queueName + ' is bound to Exchange ' + exchangeName + ' with routing key ' + routingKey);
// 在这里开始消费消息
channel.consume(queueName, function(msg) {
MyConsume.handleMessage(msg,channel);
}, {
noAck: false
});
});
});
});
});
MyConsume.js
const { UserModel } = require('./UserModel');
function handleMessage(msg,channel) {
UserModel.create({
user_name: 'Example Bookmark',
url: 'http://www.example.com',
type_id: 1,
order: 1,
is_recommend: true,
status: true
}).then(bookmark => {
console.log('New bookmark created:');
console.log(new Date());
}).catch(error => {
console.error('Error creating bookmark:', error);
});
// 在这里可以添加你的其他处理逻辑
channel.ack(msg)
}
module.exports = {
handleMessage: handleMessage
};
使用 Mysql 连接池,开 10 个 mysql 连接,消费 3 万 rabbitmq 消息,
每条消息的逻辑是往 mysql 数据表写入一条数据,30 秒写入完.
以上 nodejs 代码的写法我用 php 实现不到。
注意:
需要处理完消息手动确认消息.
123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..路人 在
php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号