aws lambda和rds工作示例(需要与sequelize一起使用)

webghufk  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(357)

这里有一个aws lambda和mysql的工作示例,但我希望它能与sequelize一起工作。如何使用aws lambda?我也有身份验证的iam角色。
https://dzone.com/articles/passwordless-database-authentication-for-aws-lambd

'use strict';
const mysql = require('mysql2');
const AWS = require('aws-sdk');
// TODO use the details of your database connection
const region = 'eu-west-1';
const dbPort = 3306;
const dbUsername = 'lambda'; // the name of the database user you created in step 2
const dbName = 'lambda_test'; // the name of the database your database user is granted access to
const dbEndpoint = 'lambdatest-cluster-1.cluster-c8o7oze6xoxs.eu-west-1.rds.amazonaws.com';
module.exports.handler = (event, context, cb) => {
  var signer = new AWS.RDS.Signer();
  signer.getAuthToken({ // uses the IAM role access keys to create an authentication token
    region: region,
    hostname: dbEndpoint,
    port: dbPort,
    username: dbUsername
  }, function(err, token) {
    if (err) {
      console.log(`could not get auth token: ${err}`);
      cb(err);
    } else {
      var connection = mysql.createConnection({
        host: dbEndpoint,
        port: dbPort,
        user: dbUsername,
        password: token,
        database: dbName,
        ssl: 'Amazon RDS',
        authSwitchHandler: function (data, cb) { // modifies the authentication handler
          if (data.pluginName === 'mysql_clear_password') { // authentication token is sent in clear text but connection uses SSL encryption
            cb(null, Buffer.from(token + '\0'));
          }
        }
      });
      connection.connect();
      // TODO replace with your SQL query
      connection.query('SELECT * FROM lambda_test.test', function (err, results, fields) {
        connection.end();
        if (err) {
          console.log(`could not execute query: ${err}`);
          cb(err);
        } else {
          cb(undefined, results);
        }
      });
    }
  });
};
xmjla07d

xmjla07d1#

我们正在使用sequelize和lambda,但是您需要保留更多的资源,在我们的示例中,我们需要至少1gb的内存来运行带有sequelize的lambda。如果没有它,仅仅使用mysql2,它的运行空间就只有128mb。
但是如果你真的想使用sequelize,只需将createconnection替换为sequelize文档中的内容
也许你会用 context.callbackWaitsForEmptyEventLoop=true 因为当您调用回调函数时可能会遇到一些问题,而您却一无所获,因为您的事件循环可能永远不会为空。

相关问题