简体   繁体   中英

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

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

I am writing answer of my own question

make database.js file in component/lib folder

code of 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

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

Can use connection variable to write mysql query like this in component/lib/index.js

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. 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.

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. Since you have a NodeJS-based runtime for your component, there should be an "index.js" file inside your Component folder -

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.

Serverless should have already included for you this entire lib/ folder in all your lambda function's handler.js code like this -

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 -

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:

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:

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.

my code snippet from 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.

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. 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. Here is the flow:

client -> registerUserLambda -> dbLambda -> DATABASE

However, the thing about lambdas is that when there are too many requests, there will be new containers created to handle other requests. That is, new connections will be created. Therefore the concept of connection pools does not work well for now on serverless lambdas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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