【问题标题】:nodejs: Does database connection cost matter?nodejs:数据库连接成本重要吗?
【发布时间】:2016-11-25 09:21:05
【问题描述】:

1.同步

mongo.conn(function(err,db){
 db.collection('pet').find({},function(err, result){
    db.collection('petviewcount').updateOne({}, {$inc:{viewcount:+1}}, function(err, result){
        // db.collection('more').find({},function(err, result){
            // db.collection('insert').find({},function(err, result){
                // db.collection('update').find({},function(err, result){
                db.close();
                cb(err, result);
    });                    
});

});

2.异步

mongo.conn(function(err,db){
    db.collection('pet').find({},function(err, result){
                db.close();
                cb(err, result);
    });
});
countUp();
// more + insert + update()

function countUp(){
  mongo.conn(function(err,db){
    db.collection('petviewcount').updateOne({}, {$inc:{viewcount:+1}}, function(err, result){
        db.close();
    });
  });
}


据我所知,向服务器(节点)发送单个请求时
第一个是节省服务器和数据库之间的连接成本。
第二个是比前一个更快的响应。

现实世界中哪个更好?
( 1. 可接受的数据延迟小
2.我不知道如何处理服务器和数据库之间的性能瓶颈。 )

【问题讨论】:

  • 你误解了同步和异步进程的概念。您的两个示例代码都是异步运行的。在性能方面,重用连接比在每个请求上创建一个新连接要好,因为建立连接需要资源和开销。
  • 如果上例中没有回调,是同步的吗?还是在使用睡眠功能或节点同步库时是同步的?我越来越糊涂了。

标签: node.js database performance connection


【解决方案1】:

在性能方面,重用连接比在每个请求上建立一个新连接要好,因为建立连接需要资源和开销。

我认为他的方法更好:

//global connection reference
var dbConnection;

//remember to wait for connection established before using the connection
mongo.conn(function(err,db){
  dbConnection = db;
  start();  //now you can run all query with one connection
});

function start() {
  findPet();
  countUp();
}

function findPet() {
  dbConnection.collection('pet').find({},function(err, result){
  });
}

function countUp(){
  dbConnection.collection('petviewcount').updateOne({}, {$inc:{viewcount:+1}}, function(err, result){
    });
}

【讨论】:

  • 感谢您的体贴:)
猜你喜欢
  • 2016-03-01
  • 2011-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多