node.js - Hapi.js Catbox Redis 返回 "server.cache is not a function"

标签 node.js caching redis hapi.js

所以我 99% 确定我只是在这里搞砸了一些愚蠢的事情。

我正在尝试设置 catbox 以将对象缓存到 redis。我已经启动并运行了 redis,我可以使用 RDM(redis 的类似 sql pro 的实用程序)访问它,但 Hapi 不合作。

我像这样注册 redis catbox 缓存:

const server = new Hapi.Server({
cache: [
{
  name: 'redisCache',
  engine: require('catbox-redis'),
  host: 'redis',
  partition: 'cache',
  password: 'devpassword'
}
]
});

我在 server.js 中执行此操作 在这段代码之后,我继续注册更多插件并启动服务器。我也在文件末尾导出服务器

module.exports = server;

然后在我的路由文件中,我尝试像这样设置一个测试路由:

{
    method: 'GET',
    path: '/cacheSet/{key}/{value}',
    config: { auth: false },
    handler: function(req, res) {
        const testCache = server.cache({
            cache: 'redisCache',
            expireIn: 1000
        });

        testCache.set(req.params.key, req.params.value, 1000, function(e) {
            console.log(e);
            res(Boom.create(e.http_code, e.message));
         })
        res(req.params.key + " " + req.params.value);
    }
},

注意:我的路由在外部文件中,并导入到我注册它们的 server.js 中。

如果我注释掉这条路线上的所有缓存内容,路线运行正常并返回我的参数。

如果我用缓存的东西运行它,一开始我得到“服务器未定义”。所以我然后添加了

const server                        = require('./../server.js');

导入服务器。

现在当我运行它时,我得到“server.cache is not a function”和 500 错误。

我不明白我做错了什么。我的猜测是我正在导入服务器,但也许它是没有设置所有配置的对象,因此它无法使用 .cache 方法。然而,这似乎是错误的,因为 .cache 应该始终是默认内存缓存的默认方法,所以即使我的缓存注册尚未激活,server.cache 理论上应该仍然是一种方法。

我知道我搞砸的一定是一些基本的东西,但是什么?

最佳答案

我是对的。我在做一些愚蠢的事情。这与我导出服务器的方式有关。我修改了我的结构以提取初始服务器创建并使其更加模块化。现在我只是像这样导出服务器:

'use strict';
const Hapi       = require('hapi');
const server = new Hapi.Server({
  cache: [
    {
      name: 'redisCache',
      engine: require('catbox-redis'),
      host: 'redis',
      partition: 'cache',
      password: 'devpassword'
    }
  ]
});
module.exports = server;

然后我将其导入我的主服务器文件(现在是 index.js,之前是 server.js),一切运行良好。我还可以将其导入任何其他文件(在本例中为我的路由文件)并访问服务器以获取适当的方法。

Redis 愉快地存储 key ,Hapi 愉快地不给我错误。

离开这里以防其他人遇到这样的愚蠢错误。

关于node.js - Hapi.js Catbox Redis 返回 "server.cache is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35368723/

相关文章:

javascript - Grunt 展开文件,src 中可接受哪些模式?

asp.net - 本地主机上的 jQuery 脚本缓存

amazon-web-services - redis 上的 keys 命令行为与 aws 上的 redis 集群

node.js - : Could not find valid key packet for encryption in key 加密时 Node openpgp错误

ruby-on-rails - Rails API Carrierwave 无法上传从 API 客户端发送的文件

android - Android 设备上的 Ionic 应用程序实时重新加载失败 : connection to the server was unsuccessful

c++ - 分析指令缓存未命中

laravel redis缓存将字符串长度添加到值

python - 将 Redis 与 Sentinel 和 redis-py 一起使用时如何故障转移到新的主节点?

redis - Kubernetes - 无法从同一集群上的另一个 pod 连接到 redis pod