首页 > 解决方案 > Hapi catbox 无法连接到 redis 服务器

问题描述

首先,我想说我是 Hapi 的新手,所以不要过分评价我。

我正在按照本教程catbox尝试使用和包设置基于 Redis 的服务器端缓存catbox-redis npm,但出现以下错误:

{
  reason: Error: Connection is closed.
      at Redis.connectionCloseHandler (/home/yuriy/dev/sources/all/hapi-getting-started/node_modules/ioredis/built/redis/index.js:305:24)
      at Object.onceWrapper (events.js:300:26)
      at Redis.emit (events.js:210:5)
      at processTicksAndRejections (internal/process/task_queues.js:75:11)
}

如您所见,它说错误在ioredis(根据 package-lock.json 的 v4.14.1)包中,它是catbox-redis.

我在本地运行 Redis 服务器。

username@my-computer:~$ redis-cli -v
redis-cli 4.0.9
username@my-computer:~$ redis-cli 
127.0.0.1:6379> ping
PONG

这是我的package.json

{
  "name": "hapi-getting-started",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "build": "rimraf dist && tsc",
    "start": "rimraf dist && tsc && node dist/index.js",
    "dev": "tsc -w | nodemon dist/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@hapi/catbox": "^10.2.3",
    "@hapi/catbox-redis": "^5.0.5",
    "@hapi/hapi": "^18.4.0",
    "rimraf": "^3.0.0",
    "typescript": "^3.7.2"
  },
  "devDependencies": {
    "@types/hapi__catbox": "^10.2.2",
    "@types/hapi__catbox-redis": "^5.0.0",
    "@types/hapi__hapi": "^18.2.6",
    "@types/node": "^12.12.14",
    "nodemon": "^2.0.1"
  }
}

这是我的src/index.ts

const Hapi = require('@hapi/hapi');
const CatboxRedis = require('@hapi/catbox-redis');

console.log(`Running environment ${process.env.NODE_ENV || 'dev'}`);

// Catch uncaught exceptions
process.on('uncaughtException', (error: Error) => {
  console.error(`uncaughtException ${error.message}`);
  console.error({ reason });
});

// Catch unhandled rejected promises
process.on('unhandledRejection', (reason: any) => {
  console.error(`unhandledRejection ${reason}`);
  console.error({ error });
});

const init = async () => {
  const server = Hapi.server({
    host: 'localhost',
    port: 8000,
    cache: {
      name: 'redis-cache',
      provider: {
        constructor: CatboxRedis,
        options: {
          partition: 'my_cached_data',
          tls: {},
        },
      },
    },
  });

  await server.start();
  console.log('Server running on %s', server.info.uri);
};

init();

任何想法我做错了什么?我在这个问题上花了很多时间,所以任何帮助都将不胜感激。

标签: node.jsredishapijsioredis

解决方案


好的, Hapi 官方文档中似乎存在关于缓存的问题(服务器端缓存部分)。解决方案非常简单但并不明显:我刚刚删除了tls: {},.

  const server = Hapi.server({
    host: 'localhost',
    port: 8000,
    cache: {
      name: 'redis-cache',
      provider: {
        constructor: CatboxRedis,
        options: {
          partition: 'my_cached_data',
          // tls: {}, <-- Here is a problem, remove this line
        },
      },
    },
  });

这是ioredis配置参数。来自catbox-redis 文档

tls- 表示ioredis的 TLS 配置选项的对象。

ioredis 您可以在docs中找到更多详细信息。


推荐阅读