使用Java使用Azure函数重用数据库连接 [英] Reusing Database Connections With Azure Functions Using Javascript

查看:52
本文介绍了使用Java使用Azure函数重用数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从用Java语言编写的Azure函数中找到有关如何管理数据库连接(在我的情况下为MongoDB)的明确信息.

I cannot find clear information on how to manage database connections (MongoDB in my case) from an Azure function written in Javascript.

下面的Microsoft文档说,不要通过使用SQL Server的.NET Framework数据提供程序在C#中使用静态变量来为函数的每次调用创建连接,并且池由客户端连接处理.它没有描述如何使用Javascript执行此操作.

The Microsoft document below says to not create a connection for each invocation of the function by using static variables in C# using .NET Framework Data Provider for SQL Server and the pooling is handled by the client connection. It does not describe how to do this in Javascript.

https://docs.microsoft.com/en-us/azure/azure-functions/manage-connections

这里介绍了一种创建全局变量以在调用之间保留数据库客户端的解决方案,但是作者不确定这是正确的方法.

A solution of creating a global variable to hold the database client between invocations is described here but the author is not confident this is the correct way to do it.

http://thecodebarbarian.com/getting-started-with-azure-functions-and-mongodb.html

有人在生产中使用过此软件,还是知道这是正确的方法?

Has anyone used this in production or understand if this is the correct approach?

推荐答案

是的,C#/SQL在静态变量中存储单个SqlConnection实例与JS/MongoDB在全局变量中存储单个Db实例之间存在非常接近的对等关系.Azure Functions中JS/MongoDB的基本模式是(假设您是最新的异步/等待-或者您可以根据链接的文章使用回调):

Yes, there's a very close equivalence between C#/SQL storing a single SqlConnection instance in a static variable and JS/MongoDB storing a single Db instance in a global variable. The basic pattern for JS/MongoDB in Azure Functions is (assuming you're up to date for async/await - alternatively you can use callbacks as per your linked article):

// getDb.js

let dbInstance;

module.exports = async function() {
    if (!dbInstance) {
        dbInstance = await MongoClient.connect(uri);
    }
    return dbInstance;
};

// function.js

const getDb = require('./getDb.js');

module.exports = async function(context, trigger) {
    let db = await getDb();
    // ... do stuff with db ..
};

这将意味着您仅实例化每个主机实例的一个Db对象.请注意,这不是每个功能应用程序一个-如果您使用的是专用的应用程序服务计划,则计划中将指定您指定的实例数量;如果您使用的是消费计划,则该数量将有所不同取决于您的应用程序的繁忙程度.

This will mean you only instantiate one Db object per host instance. Note this isn't one per Function App - if you're using a dedicated App Service Plan then there will be the number of instances you've specified in the plan, and if you're using a Consumption Plan then it'll vary depending on how busy your app is.

这篇关于使用Java使用Azure函数重用数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆