我可以看到 restful 有一个名为 Etags 的内置缓存机制,那么为什么我们需要使用 redis 或 memcached 缓存端点。加上 etags 我们可以检查资源是否已修改。
这是示例 redis 缓存代码
const getBook = (req, res) => {
let isbn = req.query.isbn;
let url = `https://www.googleapis.com/books/v1/volumes?q=isbn:${isbn}`;
return axios.get(url)
.then(response => {
let book = response.data.items;
// Set the string-key:isbn in our cache. With he contents of the cache : title
// Set cache expiration to 1 hour (60 minutes)
client.setex(isbn, 3600, JSON.stringify(book));
res.send(book);
})
.catch(err => {
res.send('The book you are looking for is not found !!!');
});
};
const getCache = (req, res) => {
let isbn = req.query.isbn;
//Check the cache data from the server redis
client.get(isbn, (err, result) => {
if (result) {
res.send(result);
} else {
getBook(req, res);
}
});
}
app.get('/book', getCache);