问题
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.
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).
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?
回答1:
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:
- Under load, multiple server instances will be allocated to run your functions. These server instances don't share any state.
- Each of your functions is deployed to different server instances. Two functions will never run on the same server instance.
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.
来源:https://stackoverflow.com/questions/52687786/firebase-functions-support-global-variable-across-functions