这是我正在使用的云功能当发货人接受订单时向店主发送通知。 但有时至少需要 20 秒才能完成,更常见的是需要 3 分钟以上。我的其他云功能运行得很好。无法找出此功能的问题。
exports.onChangeOfOrderStatus = functions.firestore
.document('orders/{documentId}')
.onUpdate(async (change, context) => {
// Get an object with the current document value.
// If the document does not exist, it has been deleted.
const document = change.after.exists ? change.after.data() : null;
// Get an object with the previous document value (for update or delete)
const oldDocument = change.before.data();
const newDocument = change.after.data();
const oldStatus = oldDocument.orderStatus;
const newStatus = newDocument.orderStatus;
functions.logger.log(oldStatus);
functions.logger.log('TO');
functions.logger.log(newStatus);
let orderPassed = false;
let shopsIds = [];
Array.prototype.push.apply(shopsIds, newDocument.shopsWhoGotOrders);
functions.logger.log("Printing shopIds 1st time");
shopsIds = getUnique(shopsIds);
printArray(shopsIds); //Code works fine and instantly at this point of line
let shopTokensAre = [];
if (oldStatus == 'prepending' && newStatus == 'pending') {
shopsIds.forEach(async result => {
await admin.firestore().collection("users")
.where('role', "==", 'shopkeeper')
.where('uid', '==', result)
.get().then(snapshot => {
snapshot.forEach(async doc => {
shopTokensAre.push(doc.data().token);
functions.logger.log("Printing shopIds: 2nd time"); // This line
//takes time to print
functions.logger.log(doc.data().token);
await admin.messaging().send({
token: doc.data().token,
notification: {
title: "Hi TELLOO Shopkeeper",
body: 'You received a new order, Please Accept/Reject it fastly',
imageUrl: 'https://support.kraken.com/hc/article_attachments/360085484571/ProApp_NewOrderButton_02082021.png',
}
})
.then(snapshot => {
functions.logger.log("Notifications sent");
});
});
});
});
}
});
我建议审查提示与技巧 https://cloud.google.com/functions/docs/bestpractices/tipsCloud Functions 指南,用于检查建议并避免使用 Cloud Functions 时出现问题。
本文件中的一些建议集中在所谓的“冷启动。函数是无状态的,执行环境往往从头开始初始化,这称为冷启动。
从您描述的问题来看,很可能是冷启动问题。您可以检查为您的函数配置的最小实例数。
默认情况下,Cloud Functions 根据传入请求的数量缩放实例数量。您可以通过设置 Cloud Functions 必须保持准备好服务请求的最小实例数来更改此默认行为。设置最小实例数可以减少应用程序的冷启动。
You can 为现有函数设置最小实例限制 https://cloud.google.com/functions/docs/configuring/min-instances#setting_minimum_instance_limits,按照以下步骤操作:
- 转到 Google Cloud Console 中的 Cloud Functions 页面:
进入云函数页面 https://console.cloud.google.com/functions
- 单击现有函数的名称即可转到其功能详情 page.
- Click Edit.
- Click 运行时、构建和连接设置扩展额外的选项。
- In the 最少实例数领域中的自动缩放部分,输入一个大于或等于 1 的数字。
- Click Next.
- Click Deploy.
此外,您可以检查依赖关系 https://cloud.google.com/functions/docs/bestpractices/tips#use_dependencies_wisely你在你的函数中使用:
因为函数是无状态的,所以执行环境通常是从头开始初始化的(在所谓的冷启动)。当发生冷启动时,将评估函数的全局上下文。
如果您的函数导入模块,这些模块的加载时间可能会增加冷启动期间的调用延迟。您可以通过正确加载依赖项而不加载函数不使用的依赖项来减少此延迟和部署函数所需的时间。
也可以看看:
- 最大限度地减少冷启动时间(Firecasts) https://www.youtube.com/watch?v=v3eG9xpzNXM
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)