首页 > 解决方案 > 如何使用谷歌云功能实例减少冷启动时间?

问题描述

使用 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时没有初始化它?

标签: javascriptfirebasegoogle-cloud-platformgoogle-cloud-functions

解决方案


你试图做的事情是不可能的。根据定义,两个服务器实例不能共享内存。它们彼此完全隔离。每个函数调用都在自己的实例中独立运行,两个不同的函数永远不能重用同一个实例。您将不得不接受 function1 的全局内存空间永远不会被 function2 看到。

观看此视频以了解更多信息:https ://www.youtube.com/watch?v=rCpKxpIMg6o


推荐阅读