代码之家  ›  专栏  ›  技术社区  ›  Rashomon

即使节点进程死亡,也要保持缓存

  •  0
  • Rashomon  · 技术社区  · 6 年前

    我的后端Nodejs必须向外部服务发出一些API GET请求调用,以检索数据并作为网页。正在缓存这些API调用。 因为我使用的是Heroku,所以每次应用程序进入休眠状态时,这些数据都会被删除。是否存在任何持久的缓存库?目前我正在使用 lru-cache axios-extensions .

    const axios = require('axios');
    const { cacheAdapterEnhancer } = require('axios-extensions');
    const LRUCache = require("lru-cache")
    
    const options = {
        defaultCache: new LRUCache({ maxAge: 60 * 60 * 1000, max: 100 })
    }
    
    const http = axios.create({
            headers: { 'Cache-Control': 'no-cache' },
            timeout: 60000,
            adapter: cacheAdapterEnhancer(axios.defaults.adapter)
        }
    )
    
    getData: async () => {
        try {
            const response = await http.get(url, config)
            const data = response.data
            return data
        } catch (error) {
            console.log(error)
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Rashomon    6 年前

    const axios = require('axios')
    const redis = require('redis')
    
    // create and connect redis client to local instance.
    const client = redis.createClient()
    
    // Print redis errors to the console
    client.on('error', (err) => {
        console.log("Error " + err)
    });
    
    const http = axios.create({
        headers: { 'Cache-Control': 'no-cache' },
        timeout: 60000
    }
    )
    
    let config = {
        headers: {
            Authorization: `Bearer ${API_KEY}`,
        }
    }
    
    let url = 'https://example.com'
    
    module.exports={
        getData: async () => {
            try {
                // Try to get response from Redis store
                const response = await client.get(url)
                return responseJSON = JSON.parse(response)
            } catch (err) {
                try {
                    const response = await http.get(url, config)
                    const data = response.data
    
                    // Save response in Redis store
                    client.setex(url, 60 * 60 * 1000, JSON.stringify(data));
                    return data
                } catch (error) {
                    console.log(error)
                }
            }
        }
    }