【问题标题】:Improving performance of inserting into Mongo from ActiveMQ提高从 ActiveMQ 插入 Mongo 的性能
【发布时间】:2016-06-16 22:48:31
【问题描述】:

以下代码的基本思想是我从 ActiveMQ Artemis 安装中读取消息并将它们插入到 MongoDB 实例中。

每秒最多可以处理一百条左右的消息,但如果我向它扔几千条消息,它就会崩溃。我的第一个猜测是数据库连接的不断打开和关闭。我是否还应该考虑使用内存存储并进行批量数据库插入?

代码都在使用 mqtt 和 mongodb npm 包的节点中运行。下面的代码,如果有什么不同的话,数据库和队列都运行在 docker 容器中。

var mqtt = require('mqtt'),
client = mqtt.connect('mqtt://mq:1883', {
    username: "*************",
    password: "*************"
}),
MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectID,
assert = require('assert'),
url = 'mongodb://db:27017/uo-readings';

client.on('connect', function () {
    client.subscribe('readings');
});

client.on('error', function(error){
    console.log(error)
});

client.on('message', function (topic, message) {

    console.log(message.toString());

    MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);

        console.log("Connected correctly to server.");

        db.collection('readings').insertOne(JSON.parse(message.toString()), function(err, result) {
            assert.equal(err, null);
            console.log("Inserted a document into the readings collection.");
        });

        client.end(function(){
            console.log("Closing Connection.");
            db.close();
        });
    });
});

【问题讨论】:

  • 你猜对了!您在每次请求时都打开一个连接,这是非常糟糕的事情。只需在 client.on 之外进行连接,就可以开始了。膨胀也是一个好主意,但你的问题肯定是连接
  • 谢谢乔纳森 - 在我的数据库连接中移动 client.on('message') 函数成功了!

标签: node.js mongodb docker activemq mqtt


【解决方案1】:

见上面@Jonathan Muller 的评论

【讨论】:

    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2016-01-05
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多