【问题标题】:Caching in an app which consumes and serves an API在使用和提供 API 的应用程序中缓存
【发布时间】:2022-11-15 19:06:13
【问题描述】:

我不知道这是否是最好的询问地点,但是。

我正在构建一个天气应用程序,它使用axios 使用 api,然后使用 express 提供服务。我想知道应该在哪里添加缓存以提高 api 的速度?是在消费的时候在axios层还是在服务的时候在快递层。

下面是我的一些上下文代码

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})
    });
    
})

【问题讨论】:

    标签: node.js express caching axios


    【解决方案1】:

    是的,通常有很多表单和层可以缓存。鉴于您正在创建一个 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 获取的。

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2016-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 2017-09-28
      • 2011-11-29
      相关资源
      最近更新 更多