【问题标题】:How to use node-redis client in node typescript如何在 node typescript 中使用 node-redis 客户端
【发布时间】:2023-01-24 19:50:31
【问题描述】:

我有一个节点打字稿项目,我在其中为下面的 Redis 连接创建了一个 TS 文件。

import { createClient } from 'redis';
import { promisify } from 'util';
import Logger from 'utils/logger';

const { REDIS_URL = 'redis://localhost:6379' } = process.env;
const options = {
    legacyMode: true,
    url: REDIS_URL,
}


const client = createClient(options);
// client.connect();

client.on('connect', () => { 
    Logger.info("Connected to Redis");
});
client.on('error', err => { 
    Logger.error('redis error: ' + err);
    init();
});

client.on('ready', err => { 
    Logger.info("redis is ready");
});

client.on('end', err => { 
    Logger.info("redis connection is ended");
});

//reconnecting
client.on('reconnecting', err => { 
    Logger.info("redis connection is reconnecting");
});


const init = async () => {
    await client.connect();
}

export { init,client };

然后我将其导入并将其连接到 index.ts

import { init } from 'dataSource/redis';


(async () => {
  await init();
})();

app.listen(PORT,() => {
    // console.log(`server is running on PORT ${PORT}`)
    Logger.info(`Server Started in port : ${PORT}!`);
})

然后我试图在我的控制器文件中使用客户端。

import {  client as redisClient } from 'datasource/redis';

redisClient.setEx("Key",Number(process.env.REDIS_EXPIRE_TIME),"VALUE");

但我收到这个错误

Error: The client is closed

【问题讨论】:

标签: node.js typescript redis node-redis


【解决方案1】:

取消注释“client.connect();”在第 13 行。

这应该使它工作

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2012-04-14
    • 2017-07-31
    • 2020-06-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多