gpt4 book ai didi

javascript - 云函数 - 如何仅实例化全局函数/变量一次?

转载 作者:行者123 更新时间:2023-12-01 01:12:03 24 4
gpt4 key购买 nike

我有一个 Firebase 应用程序,它使用 Cloud Functions 与 Google Cloud SQL 实例通信。这些云函数用于执行 CRUD 操作。我想确保数据库反射(reflect) CRUD 操作,因此,每次推送新功能代码时都运行迁移代码,以确保数据库始终是最新的。

我在全局函数中执行此操作

const functions = require('firebase-functions')
const pg = require('pg')

// Create if not exists database
(function() {
console.log('create db...')
})()

exports.helloWorld = functions.https.onRequest((request, response) => {
console.log('Hello from Firebase function log!')
response.send('Hello from Firebase!')
})

exports.helloWorld2 = functions.https.onRequest((request, response) => {
console.log('Hello from Firebase function log 2!')
response.send('Hello from Firebase 2!')
})

当我部署时,此控制台日志会运行两次。

现在我明白,无法知道 Cloud Functions 将为这些函数启动多少个实例,如其文档中所述:

The global scope in the function file, which is expected to contain the function definition, is executed on every cold start, but not if the instance has already been initialized.`

如果我添加第三个函数,此控制台日志现在会在日志中显示 3 次,而不是 2 次,每个函数显示一次。 这样说是否正确:上传的每个函数都有一个新实例?我试图了解上传一组云函数时幕后发生的情况。

如果是这样 - 是否没有可靠的方法在云函数中的全局函数内运行迁移代码?

最佳答案

您正在执行的操作不属于 Cloud Functions 支持的用例。 Cloud Functions 代码运行以响应项目中发生的事件。部署时不会发生“一次性”函数调用。如果您需要运行一次代码,只需从您的桌面或您控制的其他服务器运行即可。

您还应该努力最大程度地减少在函数的全局范围内发生的工作量。全局变量将被实例化,并为应用程序中运行函数的每个分配的服务器实例运行一次,因为每个函数都在彼此完全隔离的情况下运行,并且每个函数都有自己的所有内容副本。观看我的视频 function scaling and isolation为了更好地理解这种行为。

关于javascript - 云函数 - 如何仅实例化全局函数/变量一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55080017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com