如何在节点脚本中使用node-redis客户端

7gyucuyw  于 2023-01-25  发布在  Redis
关注(0)|答案(1)|浏览(117)

我有一个节点类型脚本项目,我已经创建了一个TS文件的Redis连接是如下。

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
h43kikqp

h43kikqp1#

取消注解“client.connect()”;“在第13行。
这应该能让它工作

相关问题