AWS Lambda 使用 firebase-admin 初始化应用程序超时

Jim*_*Jim 3 amazon-web-services firebase aws-lambda firebase-cloud-messaging firebase-admin

我使用 Lambda 到 Firebase 消息。我参考这个。但 lambda 函数仍然超时,因为它无法连接到谷歌服务器。

处理程序.js

/ [START imports]
const firebase = require('firebase-admin');
const serviceAccount = require("../serviceAccount.json");

module.exports.message = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;  
  const registrationToken = "xxxxxxx";

  const payload = {
    data: {
      score: "850",
      time: "2:45"
    }
  };

  // [START initialize]
  if(firebase.apps.length == 0) {   // <---Important!!! In lambda, it will cause double initialization.
    firebase.initializeApp({
      credential: firebase.credential.cert(serviceAccount),
      databaseURL: 'https://messaging-xxxxx.firebaseio.com'
    });
  }

  // Send a message to the device corresponding to the provided
  // registration token.
  firebase.messaging().sendToDevice(registrationToken, payload)
    .then(function(response) {
      // See the MessagingDevicesResponse reference documentation for
      // the contents of response.
      console.log("Successfully sent message:", response);
      callback(null, {
        statusCode: 200,
        body: JSON.stringify("Successful!"),
      });
    })
    .catch(function(error) {
      console.log("Error sending message:", error);
      callback(null, {
        statusCode: 500,
        body: JSON.stringify({
          "status": "error",
          "message": error
        })
      })
    });
};
Run Code Online (Sandbox Code Playgroud)

云观察

[错误:通过“credential”属性提供给initializeApp()的凭证实现无法获取有效的Google OAuth2访问令牌,并出现以下错误:“connect ETIMEDOUT 172.217.26.45:443”。]

但我使用相同的 serviceAccount.json 在我的 ec2 上运行并工作查找。有人遇到这个吗?

Jim*_*Jim 5

经过几个小时的努力,我终于找到了原因。因为我的Lambda使用VPC连接RDS并且VPC的网络接口只有私有IP。

AWS 文档

当您将 VPC 配置添加到 Lambda 函数时,它只能访问该 VPC 中的资源。如果 Lambda 函数需要同时访问 VPC 资源和公共 Internet,则 VPC 需要在 VPC 内部拥有网络地址转换 (NAT) 实例。

所以我需要在VPC内创建NAT。我关注这个博客并解决了问题。