Mat*_*out 2 caching firebase firebase-hosting google-cloud-functions google-cloud-firestore
假设我在Firestore中有一个包含100,000个内容的数据库。每个内容每月更改一次的可能性不大。我的单页应用程序使用Firebase托管,使用一个函数从Firestore检索内容,将其呈现为HTML,然后将其返回给浏览器。
如果我通常不定期处理不那么动态的内容,那将浪费我的firestore配额,并开始增加很多钱。
如何将那段内容保存为静态.com / path / path / contentpage.html文件,以便在每次请求确切的路径和查询时都可以使用,而不是每次都经过firestore /函数处理?
我的目标是提高速度,并减少不必要的存储请求,因为每次读取都会花费金钱。
谢谢!
当您在Cloud Functions for Firebase之上使用Firebase Hosting时,Hosting可以充当HTTPS函数响应之上的边缘缓存层。您可以在文档中阅读有关该集成的信息。特别是,请阅读“ 管理缓存行为 ”一节:
用于管理缓存的主要工具是Cache-Control标头。通过设置它,您可以与浏览器和CDN通讯,您的内容应缓存多长时间。在函数中,您可以这样设置Cache-Control:
Run Code Online (Sandbox Code Playgroud)res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
除了设置 Cache-Control 标头之外,您还可以利用在 Cloud Functions 实例中设置全局变量的好处,请参阅Cloud Functions 提示,其中提到“使用全局变量在以后的调用中重用对象”。
有了这个想法,我就可以使用npm 包库(是的,我确实开发了这个,但这与它碰巧与 Cloud Functions 中的这个用例一起使用的事实无关 - 如果它让你觉得我也在生产中使用它更好的)。
只要变量treasury存在,就会利用财政部的“内存”适配器来存储数据的示例,该变量与 Cloud Function 实例一起存在和消亡:
const functions = require('firebase-functions');
const tauist = require('tauist');
const Treasury = require('treasury');
const cors = require('cors')({
origin: true
});
// note that memory adapter uses MS not S for ttl
const treasury = new Treasury({
ttl: tauist.ms.thirtyMinutes
});
function getAnimalData({name}) {
// replace this with your actual Promise code doing the "real work" that you want to cache
return new Promise();
}
exports.animal = functions.https.onRequest((req, res) => {
if (req.method !== 'GET') {
return res.status(403).send('Forbidden');
}
// Enable CORS using the `cors` express middleware.
return cors(req, res, () => {
// Reading ticker symbol from URL query parameter.
let name = (req.query.name || '').trim();
console.log('animal name:', name);
if (!name) {
return res.status(400).send('Bad Request');
}
res.set('Cache-Control', `public, max-age=${tauist.s.thirtyMinutes}, s-maxage=${tauist.s.thirtyMinutes}`);
treasury.invest(getAnimalData, {name})
.then((data) => res.status(200).send(data))
.catch((error) => {
console.error('error caught:', error);
res.status(500).send('Internal Server Error');
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1863 次 |
| 最近记录: |