简体   繁体   English

nodejs + azure 函数应用程序 - 处理数据库连接的最佳实践?

[英]nodejs + azure function apps - best practice for handling db connections?

Please point me to the right forum if this is not the place to ask this (apologies in advance).如果这不是问这个的地方,请把我指向正确的论坛(提前道歉)。

I mainly want to know if, in a nodejs app, instantiating a brand new db connection inside an azure function app and then closing it each time when the function app exits, is a bad idea.我主要想知道,在nodejs应用程序中,在 azure 函数应用程序中实例化一个全新的数据库连接,然后在每次函数应用程序退出时关闭它,是否是一个坏主意。 (feels like a bad idea). (感觉是个坏主意)。

Is this standard practice, or is there a better way for keeping a connection alive across invocations of serverless functions?这是标准做法,还是有更好的方法来保持跨无服务器函数调用的连接? Or does this not matter?或者这无关紧要?

The connection in question will be at best a mongodb-native driver connection or mongoose connection talking to a cosmosdb instance.有问题的连接充其量是与 cosmosdb 实例通信的mongodb 本地驱动程序连接或mongoose连接

Creating a new database connection every time can led to poor performance performance.每次都创建一个新的数据库连接会导致性能下降。 you can add a global pointer to a Database client to retain the connection.您可以添加一个指向数据库客户端的全局指针以保留连接。 Something as shown below:如下图所示:

const mongodb = require('mongodb');

const uri = 'mongodb+srv://XYZ/test';

let client = null;

module.exports = function (context, req) {
  context.log('Running');

  let hasClient = client != null;

  if (client == null) {
    mongodb.MongoClient.connect(uri, function(error, _client) {
      if (error) {
        context.log('Failed to connect');
        context.res = { status: 500, body: res.stack }
        return context.done();
      }
      client = _client;
      context.log('Connected');
      query();
    });
  } else {
    query();
  }

  function query() {
    client.db('test').collection('tests').find().toArray(function(error, docs) {
      if (error) {
        context.log('Error running query');
        context.res = { status: 500, body: res.stack }
        return context.done();
      }

      context.log('Success!');
      context.res = {
        headers: { 'Content-Type': 'application/json' },
        body: 'Document Length ' + docs.length + ', Connection reused ' + hasClient
      };
      context.done();     
    });
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM