【问题标题】:nuxt.js - How to cache axios call at server side for all clientsnuxt.js - 如何在服务器端为所有客户端缓存 axios 调用
【发布时间】:2020-05-19 15:45:59
【问题描述】:

我正在使用 vue + nuxt.js 应用程序,我想知道是否可以为所有客户端缓存 axios webservice 调用。我必须获取一些货币参考数据,而每个客户都必须调用这些数据并没有多大意义。

有人可以给我一些提示甚至是一个例子吗?谢谢。

【问题讨论】:

    标签: vue.js caching axios nuxt.js


    【解决方案1】:

    这是最新 Nuxt 2.11 的工作解决方案,使用本地定义的模块。

    首先在nuxt.config.js中添加一个本地模块

    modules: [
       "@/modules/axCache",
    ...
    ]
    

    然后

    //  modules/axCache.js
    import LRU from "lru-cache"
    
    export default function(_moduleOptions) {
      const ONE_HOUR = 1000 * 60 * 60
      const axCache = new LRU({ maxAge: ONE_HOUR })
    
      this.nuxt.hook("vue-renderer:ssr:prepareContext", ssrContext => {
        ssrContext.$axCache = axCache
      })
    }
    

    // plugins/axios.js
    import { cacheAdapterEnhancer } from "axios-extensions"
    import LRU from "lru-cache"
    const ONE_HOUR = 1000 * 60 * 60
    
    export default function({ $axios, ssrContext }) {
      const defaultCache = process.server
        ? ssrContext.$axCache
        : new LRU({ maxAge: ONE_HOUR })
    
      const defaults = $axios.defaults
      // https://github.com/kuitos/axios-extensions
      defaults.adapter = cacheAdapterEnhancer(defaults.adapter, {
        enabledByDefault: false,
        cacheFlag: "useCache",
        defaultCache
      })
    }
    

    请注意,这适用于服务器/客户端,并且可以配置为仅在一侧工作。

    解决方案位于:https://github.com/nuxt-community/axios-module/issues/99

    【讨论】:

    • 谢谢,如果在服务器模式下使用此缓存,是否可以在客户端之间共享,或者仍然会为每个客户端创建一个缓存?
    • 其实,发现了这个,我目前正在使用这个。此外,我将 axios 与 vuex 一起使用,以将请求保持在最低限度。 gist.github.com/Tuarisa/b7c07289eb32b2a7a77be270e1c8360f你添加一个插件并安装所需的依赖项,我不知道你的多个客户端共享同一个缓存是什么意思?你能解释一下吗?
    【解决方案2】:

    这里是缓存整个页面的新解决方案

    如果你需要的话,你甚至可以缓存一致的 api like menu

    https://www.npmjs.com/package/nuxt-perfect-cache

    npm i nuxt-perfect-cache

    // nuxt.config.js
    
    modules: [
        [
            'nuxt-perfect-cache',
            {
              disable: false,
              appendHost: true,
              ignoreConnectionErrors:false, //it's better to be true in production
              prefix: 'r-',
              url: 'redis://127.0.0.1:6379',
              getCacheData(route, context) {          
                if (route !== '/') {
                  return false
                }
                return { key: 'my-home-page', expire: 60 * 60 }//1hour
              }
            }
          ]
    ]
    

    然后为所有客户端在 redis 中缓存您的 api 响应:

    asyncData(ctx) {
        return ctx.$cacheFetch({ key: 'myApiKey', expire: 60 * 2 }, () => {
          console.log('my callback called*******')
          return ctx.$axios.$get('https://jsonplaceholder.typicode.com/todos/1')
        })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2012-08-09
      • 2019-04-10
      • 2014-12-02
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多