解决 AWS nodejs访问dynamodb 访问慢的问题

卢知
2023-12-01

原来的写法,默认大概每次60ms 


const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'cn-north-1'});

exports.handler = async (event) => {
    let startTime = Date.now();
    
    var params = {
      TableName: 'TableName',
      Key: {
        'sid': 'xxxxxxxxxxxxxx'
      }
    };
    
    let res2 = await docClient
    .get(params)
    .promise()
    .then(res => {
      return res;
    })
    .catch(err => {
      console.log("res", err);
    });
    
    // 返回值
    const response = {
        statusCode: 200,
        body: JSON.stringify(res2),
    };
    
    return response;
};

参考https://theburningmonk.com/2019/02/lambda-optimization-tip-enable-http-keep-alive/

修改后首次以外每次可以控制在10ms一下

var https = require('https');
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient({ region: 'cn-north-1',

  httpOptions: {
    agent: new https.Agent({
      rejectUnauthorized: true,
      keepAlive: true
    })
  }
  
});

还是没法做到aws吹嘘的1ms级别

 类似资料: