Firebase 函数 gen2 不缓存全局变量

问题描述 投票:0回答:1

我正在尝试通过缓存来减少函数执行时间。为此,我在需要时懒惰地将模块导入全局范围,然后重用它。

我尝试遵循本指南:https://firebase.google.com/docs/functions/tips#do_lazy_initialization_of_global_variables

以及这篇博文:https://medium.com/firebase-developers/organize-cloud-functions-for-max-cold-start-performance-and-readability-with-typescript-and-9261ee8450f0

根据我的理解,全局变量应该被缓存,但是如果我将函数保留过夜,第一次运行会触发导入,这很慢。后续调用将重用导入。

我希望只要函数由于“minInstance”参数而“活动”,实例就应该重用 init。

这是代码:

let BigImport;
export const dostuff = functionsV2_onCall(
    {
        memory: '2GiB',
        minInstances: 1,
        maxInstances: 50,
    },
    async request => {
        console.time('timing - IMPORT');
        if (!BigImport) {
            console.log('actually importing!');
            BigImport = await import('./BigImport');
        } else {
            console.log('not importing yaaaay!');
        }
        console.timeEnd('timing - IMPORT');

        const result = await BigImport.default.foo(request);
        return result;
    },
);

以下是GCP中的功能详细信息:

node.js firebase google-cloud-functions cold-start
1个回答
0
投票

但是如果我将函数保留过夜,则第一次运行会触发导入

minInstances 不能保证同一个实例始终运行。 Cloud Functions 可以在认为合适时自由关闭和重新启动实例。因此,您无法消除冷启动时间 - 您所能做的就是尽量减少冷启动发生的次数。

来自文档(强调我的):

为了最小化冷启动的影响,Cloud Functions 尝试在处理请求后将函数实例保持空闲状态未指定的时间。在此空闲时间内,打开的数据库连接等资源可能会被保留,以防需要处理另一个请求。

这里所有的粗体字都表明无法保证实例的持续运行时间与您预期的一样长。您只能最大限度地减少冷启动 - 而无法消除它们。

如果您不愿意接受任何冷启动行为,那么您将需要使用普通的配置服务器并接受随之而来的金钱和维护成本。

© www.soinside.com 2019 - 2024. All rights reserved.