为什么在部署后Google Cloud Function会多次运行全局函数? [英] Why does Google Cloud Function run a global function multiple times after deploy?

查看:41
本文介绍了为什么在部署后Google Cloud Function会多次运行全局函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了多个触发器,例如:

I have set multiple triggers, like:

exports.doSomething = functions.firestore.document('col/{doc}').onCreate(event => {})

比起我要部署的功能,我想立即运行它.看起来像这样:

Than I have a function that I want to run instant when I deployed. That looks something like this:

now()
function now(){
    console.log("running function")
}

我在日志中得到了这个

为什么它会运行很多次并被其他函数调用?

Why does it run so many times and gets called by other functions?

完整的代码,仅对其进行了测试,运行函数被调用了4次,与我设置的触发器相同:

Full code, just tested it and running function gets called 4 times, the same amount as triggers I have set:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore()
var geoip = require('geoip-lite');

exports.z = functions.firestore.document('converasdassdtIP/{UID}').onCreate(event => { })
exports.x = functions.firestore.document('sads/{UID}').onCreate(event => { })
exports.n = functions.firestore.document('asdasasdsa/{UID}').onCreate(event => { })
exports.m = functions.firestore.document('converasdasddtIP/{UID}').onCreate(event => { })

now()
function now(){
    console.log("running function")
}

推荐答案

Cloud Functions不能提供一种在部署时运行少量代码的方法.您的函数显然要多次运行,并且您应该期望它运行甚至更多次,因为新服务器实例与项目负载一起被分配(并销毁).这就是云功能扩展的方式.绝对不是只有一个服务器实例可以处理您的所有请求.您应该期望任何全局代码都可以重复运行.

Cloud Functions doesn't provide a way to run a bit of code at the time of deploy. Your function is obviously being run multiple times, and you should expect it to be run even more times as new server instances are allocated (and destroyed) in tandem with the load on your project. This is how Cloud Functions scales. There is definitely not just one server instance handling all your requests. You should expect any global code to be run repeatedly.

如果要在部署后只运行一次代码,请执行导出的功能(可能是HTTPS)并在部署后触发它.也许您可以编写一个脚本,该脚本既可以部署代码,又可以使用curl或您选择的其他机制触发该函数.

If you want to run some code exactly once after deploy, make an exported funciton (maybe HTTPS) and trigger it after you deploy. Maybe you could write a script that both deploys your code then triggers the function with curl or some other mechanism you choose.

这篇关于为什么在部署后Google Cloud Function会多次运行全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆