我不知道這是否是最好的詢問地點,但是。
我正在構建一個天氣應用程式,它使用一個 api axios,然后使用 express 為它提供服務。我想知道應該在哪里添加快取以提高 api 的速度?是消費時在 axios 層,還是服務時在 express 層?
下面是我的一些背景關系代碼
import { weatherApiKey } from 'config';
import axios from 'axios';
const forecast = (location, service) => {
console.log('inside api calling location: ', location);
axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${weatherApiKey}`)
.then(res => {
service(undefined, res.data)
})
.catch(err => {
service('Error calling weather API');
})
}
module.exports = forecast;
然后我通過以下方式提供消費的 api。
app.get('/weather', (req, res) => {
const locale = req.query.locale;
if(!locale) {
return res.send({
error: 'Please provide valid locale'
})
}
foreCast(locale, (err, weatherData) => {
if(err) {
console.log('error in calling weather API')
res.send({err});
}
console.log('returning weather data', weatherData)
res.send({weatherData})
});
})
uj5u.com熱心網友回復:
是的,通常有很多表單和層可以快取。鑒于您正在創建一個 API,我希望盡可能靠近消費者應用一些快取。這可能是在 CDN 級別。然而,一個快速簡單的答案是為您的 Express 應用程式添加一些東西作為可快取的中間件。
填充和使快取失效的方法有很多,您需要特別注意為您的用例規劃這些方法。盡可能不要過早地使用快取進行優化。它引入了復雜性、依賴性,并且在應用大量快取層時可能導致難以除錯的問題。
但是一個簡單的例子是這樣的:
'use strict'
var express = require('express');
var app = express();
var mcache = require('memory-cache');
app.set('view engine', 'jade');
var cache = (duration) => {
return (req, res, next) => {
let key = '__express__' req.originalUrl || req.url
let cachedBody = mcache.get(key)
if (cachedBody) {
res.send(cachedBody)
return
} else {
res.sendResponse = res.send
res.send = (body) => {
mcache.put(key, body, duration * 1000);
res.sendResponse(body)
}
next()
}
}
}
app.get('/', cache(10), (req, res) => {
setTimeout(() => {
res.render('index', { title: 'Hey', message: 'Hello there', date: new Date()})
}, 5000) //setTimeout was used to simulate a slow processing request
})
app.get('/user/:id', cache(10), (req, res) => {
setTimeout(() => {
if (req.params.id == 1) {
res.json({ id: 1, name: "John"})
} else if (req.params.id == 2) {
res.json({ id: 2, name: "Bob"})
} else if (req.params.id == 3) {
res.json({ id: 3, name: "Stuart"})
}
}, 3000) //setTimeout was used to simulate a slow processing request
})
app.use((req, res) => {
res.status(404).send('') //not found
})
app.listen(process.env.PORT, function () {
console.log(`Example app listening on port ${process.env.PORT}!`)
})
注意:這是使用memory-cache npm 包從https://medium.com/the-node-js-collection/simple-server-side-cache-for-express-js-with-node-js-45ff296ca0f0獲取的.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534591.html
標籤:节点.js表示缓存公理
上一篇:Exceljs,將Excel作業簿保存到所需的檔案路徑
下一篇:insertId顯示為未定義
