AWS Lambda数据库连接问题[更新的问题]

问题描述 投票:0回答:1

我有一个aws lambda函数,当它命中请求时返回null。在建立数据库连接之前,对请求的测试一直有效。关于为什么它没有运行请求的任何想法?

日志显示就绪状态为1,然后返回null。

***编辑

这是第一个问题,一旦我答应过,在执行架构方法之前,数据库连接就会消失。我会在下面回答。

const request = require('request')
const tickerController = require('./controllers/ticker');

const mongoose = require('mongoose');

let conn = null;

const uri = `mongodb+srv://${process.env.dbUser}:${process.env.dbPassword}@cluster0-oj6p1.mongodb.net/test?retryWrites=true&w=majority`;

exports.handler = async function main(event, context, lambdaCallback) {
  // Make sure to add this so you can re-use `conn` between function calls.
  // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
    context.callbackWaitsForEmptyEventLoop = false;

    // Because `conn` is in the global scope, Lambda may retain it between
    // function calls thanks to `callbackWaitsForEmptyEventLoop`.
    // This means your Lambda function doesn't have to go through the
    // potentially expensive process of connecting to MongoDB every time.
    if (conn == null) {
      conn = await mongoose.createConnection(uri, {
        // Buffering means mongoose will queue up operations if it gets
        // disconnected from MongoDB and send them when it reconnects.
        // With serverless, better to fail fast if not connected.
        bufferCommands: false, // Disable mongoose buffering
        bufferMaxEntries: 0, // and MongoDB driver buffering
        useUnifiedTopology: true,
        useNewUrlParser: true
      });
      // conn.model('Test', new mongoose.Schema({ name: String }));
      // console.log(conn);
      console.log(conn.readyState);

      runRequest(lambdaCallback);
  // })
  }
};

function runRequest(lambdaCallback) {
  request('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=BKUH&apikey=' + process.env.apiKey, (err, response, body) => {
        console.log('Request ran');
        if (err) {
          console.error(err);
          done(502, '{"message", "Error retrieving ticker data"}', 'application/json', lambdaCallback);
        } else {
          try {
            .....
node.js mongodb amazon-web-services lambda request
1个回答
0
投票

我将开始使用promises / async / await而不是回调模式。有点像

const request = require("request");
const tickerController = require("./controllers/ticker");

const mongoose = require("mongoose");

let conn = null;

const uri = `mongodb+srv://${process.env.dbUser}:${process.env.dbPassword}@cluster0-oj6p1.mongodb.net/test?retryWrites=true&w=majority`;

exports.handler = async event => {
  // Make sure to add this so you can re-use `conn` between function calls.
  // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
  context.callbackWaitsForEmptyEventLoop = false;

  // Because `conn` is in the global scope, Lambda may retain it between
  // function calls thanks to `callbackWaitsForEmptyEventLoop`.
  // This means your Lambda function doesn't have to go through the
  // potentially expensive process of connecting to MongoDB every time.
  if (conn == null) {
    conn = await mongoose.createConnection(uri, {
      // Buffering means mongoose will queue up operations if it gets
      // disconnected from MongoDB and send them when it reconnects.
      // With serverless, better to fail fast if not connected.
      bufferCommands: false, // Disable mongoose buffering
      bufferMaxEntries: 0, // and MongoDB driver buffering
      useUnifiedTopology: true,
      useNewUrlParser: true
    });
    // conn.model('Test', new mongoose.Schema({ name: String }));
    // console.log(conn);
    console.log(conn.readyState);

    const body = await runRequest();
    return body;
    // })
  }
};

function runRequest() {
  return new Promise((resolve, reject) => {
    request(
      "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=BKUH&apikey=" +
        process.env.apiKey,
      (err, response, body) => {
        console.log("Request ran");
        if (err) {
          console.error(err);
          reject(err);
        }
        resolve(body);
      }
    );
  });
}

热门问题
推荐问题
最新问题