Firebase 函数:支持跨函数的全局变量 [英] Firebase Functions: Support Global variable across functions

查看:18
本文介绍了Firebase 函数:支持跨函数的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 http firebase 函数中缓存最近的记录(比如最近 24 小时).在 http firebase 函数(比如 fetchLastXRecords)中,如果未找到从数据库中获取并设置缓存,我会在缓存中查找记录(定义的全局变量来存储记录).

I want to cache most recent records (say last 24 hrs) in a http firebase function. In a http firebase function (say fetchLastXRecords), I look for the record in cache (defined Global variable to store the records) if not found fetch from database and set cache.

当我想更新任何缓存记录时出现问题,因为其他 Firebase 函数(可能是实时数据库更改触发器)无法访问此全局变量.

Problem arises when I want to update any record of cache because this Global variable is not accessible by other firebase functions (could be real time database change triggers).

什么是更新缓存中记录的好方法?我可以调用缓存 http firebase 函数并传递更新的记录吗?或者我可以将更新的记录存储在数据库中,然后缓存功能在数据库中查找并更新缓存记录?

What could be a good approach to update the records in cache? May be I can invoke the caching http firebase function and pass the updated records? or I can store the updated records in database and later caching function look in database and update the cache records?

推荐答案

在 Cloud Functions 中,您无法确保代码中存在可供函数访问的全局变量.关于 Cloud Functions 的工作原理,您需要了解两件事:

In Cloud Functions, you have no ability to ensure that there is a global variable in your code that's accessible by your functions. There are two things you need to know about how Cloud Functions works:

  1. 在负载下,将分配多个服务器实例来运行您的功能.这些服务器实例不共享任何状态.
  2. 您的每个功能都部署到不同的服务器实例.两个函数永远不会在同一个服务器实例上运行.

因此,如果您有任何值要在函数之间共享,您应该使用持久性机制,例如数据库.当您的函数需要读取和写入共享值时,它们应该访问数据库.此外,他们应该使用某种原子事务来确保多个并发读写是安全的.

As a result, if you have any values to share between functions, you should use a persistence mechanism, such as a database. When your functions need to read and write a shared value, they should access the database. Also, they should use some sort of atomic transaction to make sure that multiple concurrent reads and writes are safe.

这篇关于Firebase 函数:支持跨函数的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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