javascript - 如何使用谷歌云功能实例减少冷启动时间?
问题描述
使用 firebase,您可以在多个文件中编写云函数。
我有两个函数,名为“function1”和“function2”,位于两个单独的文件中。
文件:function1.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
exports.function1 = functions.https.onRequest((request, response) => {
// ...
});
文件:function2.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
const admin = require('firebase-admin');//This will be executed regardless of the function called
exports.function2 = functions.https.onRequest((request, response) => {
// ...
});
现在我使用index.js来导出这些文件,如下所示。
文件:index.js
const function1 = require('./function1');
const function2 = require('./function2');
exports.function1 = function1.function1;
exports.function2 = function2.function2;
当我执行function1时,我可以从function2访问“admin”变量。
明显的解决方法是不在全局范围内声明变量。
修改文件:function2.js
const functions = require('firebase-functions');//This will be executed regardless of the function called
exports.function2 = functions.https.onRequest((request, response) => {
const admin = require('firebase-admin');//This will only be executed when function2 is called
// ...
});
现在“admin”变量仅在我调用function2而不是function1时才被初始化。
Cloud Functions 通常会回收先前调用的执行环境。
如果您在全局范围内声明变量,则其值可以在后续调用中重用,而无需重新计算。
但是现在“admin”变量将不会在后续调用中被重用,因为它没有在全局范围内声明。
所以我的问题是如何将“admin”变量存储在全局范围内(以便它可以被多个实例重用),但在调用function1时没有初始化它?
解决方案
你试图做的事情是不可能的。根据定义,两个服务器实例不能共享内存。它们彼此完全隔离。每个函数调用都在自己的实例中独立运行,两个不同的函数永远不能重用同一个实例。您将不得不接受 function1 的全局内存空间永远不会被 function2 看到。
观看此视频以了解更多信息:https ://www.youtube.com/watch?v=rCpKxpIMg6o
推荐阅读
- macos - SwiftUI onCommit 不会将光标移动到下一个文本字段 - MacOS 应用程序
- excel - 如何将我的代码正确地分配给按钮?
- azure - Azure Devops 管道无法访问 Docker Windows 映像?
- android - 如何设置 ChipNavigationBar 的文字颜色
- scala - 通过 Flink 在 Kafka 中动态写入多个 topic 异常处理
- ios - 是否可以将创建领域数据库的脚本从 JSON 添加到我的项目中?
- amazon-web-services - AWS IoT Core Basic Ingest 识别超出的 qoutas
- python - 尽管使用了兼容版本,但 Tensorflow 2.4.0 未检测到 GPU
- sql - 检查 SQL Server 中的视图
- django - 当我使用 git 在 heroku 中提交更改时,我的 django 对象会受到影响