AWS Lambda和SQL Server集成

时间:2015-10-16 07:41:52

标签: sql-server amazon-web-services aws-lambda

我的应用程序使用MS Sql Server。在了解了AWS Lambda之后,我想将我的应用程序转移到AWS Lambda以获得无服务器架构。

但正如我所提到的,应用程序使用的是Sql Server。所以我不确定AWS Lambda是否支持与Sql Server的连接。

任何评论/链接都会有所帮助。

2 个答案:

答案 0 :(得分:0)

是的,你可以从lambda连接到sql server,据我所知,几乎任何其他数据库。你在lambda函数中可以做什么的限制很少。

答案 1 :(得分:0)

这是一些示例样板,带有注释,可用于从Lambda连接到MS SQL Server数据库(假设使用NodeJS作为您的语言)。

const sql = require('mssql');

exports.handler = async (event, context, callback) => {

    let lookupValue = event.lookupValue;

    // Take DB Config from environment variables set in Lambda config
    const config = {
        user: process.env.DB_USERNAME,
        password: process.env.DB_PASSWORD,
        server: process.env.DB_SERVER,
        database: process.env.DB_DATABASE,
        options: {
            encrypt: true // Use this if you're on Windows Azure
        }
    }

    try {
        // Open DB Connection
        let pool = await sql.connect(config)

        // Query Database
        let result = await pool.request()
            .input('lookupValue', sql.Int, lookupValue)
            .query('select * from exampleTable where id = @lookupValue');

        // Close DB Connection
        pool.close();

        // The results of our query
        console.log("Results:", result.recordset);

        // Use callback if you need to return values from your lambda function.
        // Callback takes (error, response?) as params.
        callback(null, result.recordset);
    } catch (err) {
        // Error running our SQL Query
        console.error("ERROR: Exception thrown running SQL", err);
    }

    sql.on('error', err => console.error(err, "ERROR: Error raised in MSSQL utility"));
}

注意:您需要将运行mssql所需的node_modules上传到函数中。我发现最简单的方法是将整个文件夹(您的主要[通常为index.js]函数文件以及package.json和您的node_modules文件夹)压缩在一起,然后使用aws-cli上传:

aws lambda update-function-code --function-name your-function-name-here --zip-file your-zipped-project-directory.zip 

最后,确保您的数据库能够接受来自AWS Lambda函数的连接。最好的方法是结合使用AWS的VPC,NAT和Elastic IP设置-有关示例示例,请参见此博客文章:https://medium.com/@matthewleak/aws-lambda-functions-with-a-static-ip-89a3ada0b471