简体   繁体   English

带有节点MySQL的无服务器框架

[英]Serverless Framework with Node MySQL

How to use mysql connection with serverless framework.connection should be available in my component functions without creating mysql connection each time in component function 如何在无服务器框架中使用mysql连接。连接应该在我的组件函数中可用,而无需每次在组件函数中创建mysql连接

Tried like this 试过这样

var mysql  = require('mysql');

module.exports.respond = function(event, cb) {

   var pool      =    mysql.createPool({
        connectionLimit : 100,
        host     : 'hostname',
        user     : 'username',
        password : 'password',
        database : 'databasename',
        debug    :  false
    });
    var message='';
    pool.getConnection(function(err,connection){
        if(err) {
            message='Could not connect to database';
        } else {
            message="Database is connected";
        }
        var response = {
            message: message
        };
        return cb(null, response);
    });


};

but above code will be only available for current function,want to make common thing for mysql connection in serverless framework,can not find proper document about how to use mysql in serverless framework 但是上面的代码仅适用于当前功能,想在无服务器框架中使mysql连接变得通用,找不到关于如何在无服务器框架中使用mysql的适当文档

I am writing answer of my own question 我正在写我自己的问题的答案

make database.js file in component/lib folder component/lib文件夹中创建database.js文件

code of database.js database.js代码

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'hostname',
    user     : 'username',
    password : 'password',
    database : 'databasename'
});

connection.connect();
module.exports = connection;

created object like this in component/lib/index.js file component/lib/index.js文件中创建了这样的对象

var connection = require("../lib/database.js");

Can use connection variable to write mysql query like this in component/lib/index.js 可以使用连接变量在component/lib/index.js编写这样的mysql查询

module.exports.respond = function(event, cb) {

    var query="SELECT * from table_name";

    connection.query(query,function(err,rows) {

    })
};

I believe you have a Component created in your Serverless Framework based project that contains multiple lambda functions. 我相信您在基于Serverless Framework的项目中创建了一个包含多个lambda函数的组件。 And now you want to write the MySQL connection code such that this code block is available for re-use in all your lambda functions of that component. 现在,您要编写MySQL连接代码,以使该代码块可在该组件的所有lambda函数中重复使用。

If this is the ask, then Serverless does provide a "lib" folder inside your Component directory, which you can utilize to write common code logic to be re-used. 如果这是要问的问题,那么Serverless确实会在Component目录中提供一个“ lib”文件夹,您可以利用该文件夹编写要重复使用的通用代码逻辑。 Since you have a NodeJS-based runtime for your component, there should be an "index.js" file inside your Component folder - 由于您的组件具有基于NodeJS的运行时,因此Component文件夹中应该有一个“ index.js”文件-

your_serverless_project_directory/component_name/lib/index.js

The first thing you want to do is to add the MySQL connection code logic to a function/method in index.js. 您要做的第一件事是将MySQL连接代码逻辑添加到index.js中的函数/方法中。

Serverless should have already included for you this entire lib/ folder in all your lambda function's handler.js code like this - Serverless应该已经为您所有lambda函数的handler.js代码中包括了整个lib /文件夹,如下所示-

var lib = require('../../lib');

Therefore, the next/final thing you want to do is re-use your connection function/method (in all the lambda functions belonging inside your Component) like this - 因此,您要做的下一个/最后一件事是重新使用连接函数/方法(在属于组件内部的所有lambda函数中),如下所示:

module.exports.handler = function(event, context) {
  lib.mySQLConnection();
};

Hope this helps, let me know how it goes. 希望这会有所帮助,让我知道如何进行。

To build off of Normal Goswami's answer: 要建立普通戈斯瓦米人的答案:

You've specified the database here in the connection. 您已经在此处的连接中指定了数据库。 My lambdas each need different databases, so in the connection code just leave off the database: 我的lambda每个都需要不同的数据库,因此在连接代码中只需删除数据库即可:

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'hostname',
    user     : 'username',
    password : 'password'
    // no database here
});

connection.connect();
module.exports = connection;

And then use an oddly named function to change the database in each lambda function: 然后使用一个奇怪的函数来更改每个lambda函数中的数据库:

connection.changeUser({database: database}, function(err) {
    if (err) { throw err; }
});

connection.query(sql, function(err, rows, fields) {
    // etc
}

You could also look into using a database connection pool . 您还可以考虑使用数据库连接池

you have to make connection out of function, as we are doing it with mongodb we are making mongodb connection out side of Lambda Function. 您必须使连接失去功能,因为我们正在使用mongodb进行连接,因此我们正在Lambda Function之外进行mongodb连接。

my code snippet from https://github.com/malikasinger1/serverles-practice/tree/master/mongodb-connection : 我来自https://github.com/malikasinger1/serverles-practice/tree/master/mongodb-connection的代码段:

var mongoose = require("mongoose");
var dbURI = 'mongodb://localhost/mydatabase';

mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {//connected
    console.log("Mongoose is connected");
    // process.exit(1);
});

module.exports.signup = (event, context, cb) => {

    //doing signup here
}

in your cace it will be something like this most probably: 在您的面前,很可能是这样的:

var mysql  = require('mysql');

//make connection here
var pool   = mysql.createPool({
    ...
});

pool.getConnection(function(err,connection){
    ...
});

module.exports.respond = function(event, cb) {     
    //use connection here
};

I am assuming you are using serverless framework on AWS. 我假设您正在AWS上使用无服务器框架。

Although you can create a connection and assign it to a frozen variable, it's not guaranteed that your lambda won't create a new connection. 尽管您可以创建一个连接并将其分配给冻结变量,但不能保证您的lambda不会创建新连接。 Here is why: The best way so far (in my personal opinion) is to create a separate lambda function for db related operations and invoke this function through other lambdas. 原因如下:到目前为止(以我个人观点),最好的方法是为与数据库相关的操作创建一个单独的lambda函数,然后通过其他lambda调用此函数。 Here is the flow: 流程如下:

client -> registerUserLambda -> dbLambda -> DATABASE 客户端-> registerUserLambda-> dbLambda->数据库

However, the thing about lambdas is that when there are too many requests, there will be new containers created to handle other requests. 但是,关于lambda的问题是,当请求过多时,将创建新的容器来处理其他请求。 That is, new connections will be created. 即,将创建新的连接。 Therefore the concept of connection pools does not work well for now on serverless lambdas. 因此,连接池的概念目前在无服务器的lambda上不能很好地工作。

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

相关问题 带有 Node MySQL 的无服务器框架:PROTOCOL_INCORRECT_PACKET_SEQUENCE 错误 - Serverless Framework with Node MySQL: PROTOCOL_INCORRECT_PACKET_SEQUENCE error 使用Node连接到Aurora MySQL无服务器 - Connecting to Aurora MySQL Serverless with Node 无服务器框架、打字稿、nodejs 和 mysql - 错误:接收到的数据包顺序错误 - serverless framework, typescript, nodejs and mysql - Error: Received packet in the wrong sequence node.js的mysql框架 - mysql framework for node.js Mysql utf8mb4 连接字符串(Node.js,serverless-mysql 包) - Mysql utf8mb4 connection string (Node.js, serverless-mysql package) 使用 Typescript 和 MySql 的无服务器框架连接 AWS API Gateway 、Lambda 和 Cognito 的简单项目 - Serverless Framework with Typescript and MySql simple Project to connect AWS API Gateway ,Lambda and Cognito 通过Node.js与RDS MySQL / Aurora无服务器群集的SSL连接失败 - SSL connections to RDS MySQL/Aurora serverless cluster fail with Node.js 现有MYSQL DB的节点RESTAPI框架 - Node RESTAPI framework for existing MYSQL DB 在 Aurora AWS Serverless MySQL 上启用 SSL - Enable SSL on Aurora AWS Serverless MySQL 在AWS Serverless上与Node.js + MySQL同步 - Make synchronous with nodejs + mysql on aws serverless
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM