【问题标题】:memory caching with catbox and hapi js使用 catbox 和 hapi js 进行内存缓存
【发布时间】:2026-02-03 16:00:01
【问题描述】:

我正在使用 catbox 在 hapijs 中进行内存缓存,在这些情况下应该向 DB 请求获取所有行

  • 请求一个不在缓存的 db_result 行中的键,然后调用 DB 并更新缓存并从缓存对象返回值
  • 请求缓存的 db_result 行中的键返回键的值

例如:如果缓存的db_result[{ id: 12, name: 'app4' },{ id: 21, name: 'app5' }] 并且key12,则不应调用DB,否则如果键为13,则应进行DB 调用并且@987654326 @应该得到更新。

有没有关于如何配置此功能的示例。我遵循的准则正确吗?

请注意,我们在 hapi 之上使用胶水进行服务器配置。

【问题讨论】:

    标签: node.js caching hapijs


    【解决方案1】:

    有一个使用 Cache-mongodb 的示例 on Github,但 API 与任何缓存提供程序一致。

    // wildcard route that responds all requests
    // either with data from cache or default string
    server.route({
      method: 'GET',
      path: '/{path*}',
      handler: async (request, h) => {
    
          const key = {
              segment: 'examples',
              id: 'myExample'
          };
    
          // get item from cache segment
          const cached = await Cache.get(key);
    
          if (cached) {
              return `From cache: ${cached.item}`;
          }
    
          // fill cache with item
          await Cache.set(key, { item: 'my example' }, 5000);
    
          return 'my example';
      }
    });
    
    

    【讨论】: