首页 > 解决方案 > 组件内部 API 调用的 Nuxtjs Redis 缓存实现

问题描述

我正在使用插件Nuxt Perfect Cache将我的 QPI 请求缓存到外部服务。

我在组件级别使用 cacheFetch 方法,并且该组件加载到动态页面(由其 slug 定义)上。当我导航到动态页面时,API 调用不会缓存在 Redis 中,但是当我重新加载页面时,缓存会按预期发生。以下是我的代码的结构:

_slug.js(用于 /users)

<template>
  <h1>{{ user.name }}</h1>
  <Posts :author = user.id>
</template>

<script>
import Posts from '~/components/Posts.vue'
export default {
  components: { Posts },
  async asyncData({params}) {
    const user = await fetch(`/users/${params.slug}`)
    .then(res => res.json())
  }
}
</script>

在 Posts.vue 中,我使用完美的缓存 cacheFetch 方法来获取帖子列表,例如:

props: ['author'],
async fetch() {
  this.posts = await this.$cacheFetch({ key:`user--#{this.author}--posts`, expire: 60 * 60 },
    async () => {
      return await fetch(`/users/#{this.author}/posts`).then(res => res.json())
    })
},
data() {
  return {
    posts: []
  }
}

当我直接在浏览器中加载用户页面时,帖子的 json 响应按预期保存在 Redis 中。当我使用 NuxtLink 从应用程序中导航时,用户页面正确显示(包括帖子),但没有设置或从 Redis 获取密钥。

当用户与应用交互时,如何确保 API 调用被缓存?

标签: redisnuxt.jsnuxtjs

解决方案


当您在客户端导航时,redis 仅在服务器端而不是客户端可用您无权访问 redis 您可以设置绝对链接以在用户导航时呈现服务器端,但我不推荐这样做。最好的解决方案是在你的 api 中的 redis 中缓存数据。


推荐阅读