我正在使用 Redis 在我的项目中存储会话。
在
app.js
var client = redis.createClient();
client.on('error', function (err) {
console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
console.log('connected to redis successfully');
});
在我的
routes.js
文件中,我必须从redis获取所有信息,所以我使用以下内容:
var client = redis.createClient();
client.on('error', function(err){
console.log('Something went wrong ', err)
});
但是每次都是连接到redis。我怎样才能在我的
app.js
中连接一次redis并在任何地方使用它。请提出想法。预先感谢。
编辑
app.js
module.exports.client = client;
routes.js
var client = require("../app.js").client;
client.hgetall();
但是我收到了
error
TypeError: Cannot read property 'hgetall' of undefined
在
app.js
var client = redis.createClient();
client.on('error', function (err) {
console.log('could not establish a connection with redis. ' + err);
});
client.on('connect', function (err) {
console.log('connected to redis successfully');
});
module.exports = { client }
在
routes.js
var { client } = require('./app');
client.on('error', function(err){
console.log('Something went wrong ', err)
});
(假设
app.js
和routes.js
在同一级目录)
编辑:修复了一些错字
app.js
const redis = require('redis'),
redisClient = redis.createClient(6379, '127.0.0.1');
const http = require('http');
const REDIS_USER_DATA_INDEX = 2;
redisClient.select(REDIS_USER_DATA_INDEX);
module.exports.client = redisClient;
routes.js
const app = require('./app');
app.client.on('connect', function () {
console.log('redis connected');
console.log(`connected ${app.client.connected}`);
}).on('error', function (error) {
console.log(error);
});
我希望这能解决您的问题。谢谢
之前提供的响应很好,但不如传统的单例。 A singleton 是一个只允许创建其自身的单个实例并提供对所创建实例的访问权限的类。在面向对象编程中,它是一种设计模式。下面的代码片段可以被认为是在 Node.js 中实现单例类的尝试。
import { createClient } from "redis";
import logger from "./logger";
import "dotenv/config";
export type RedisClientType = ReturnType<typeof createClient>;
export class RedisInstance {
private static instance: RedisInstance;
private static CacheClient: RedisClientType;
//Database Credentials
private REDIS_URL: string = process.env.REDIS_URL!;
private REDIS_USERNAME: string = process.env.REDIS_USERNAME!;
private REDIS_PASSWORD: string = process.env.REDIS_PASSWORD!;
private REDIS_PORT: string = process.env.REDIS_PORT!;
private RedisClient = createClient({
username: this.REDIS_USERNAME,
password: this.REDIS_PASSWORD,
socket: {
host: this.REDIS_URL,
port: Number(this.REDIS_PORT),
},
});
// Constructor
private constructor() {
logger.warn("🔺 New Redis Client Instance Created!!");
}
private async initialize() {
try {
if (
!this.REDIS_URL ||
!this.REDIS_USERNAME ||
!this.REDIS_PASSWORD ||
!this.REDIS_PORT
) {
logger.error("🚫 Redis ENV is not set!!");
}
RedisInstance.CacheClient = await this.RedisClient.connect();
const clientId = await RedisInstance.CacheClient.sendCommand([
"CLIENT",
"ID",
]);
logger.info(`✅ Connected to Redis with ID: ${clientId}`);
} catch (err) {
logger.error("❌ Could not connect to Redis\n%o", err);
throw err;
}
}
//Singleton Function Implement
public static getInstance = async (): Promise<RedisInstance> => {
if (!RedisInstance.instance) {
RedisInstance.instance = new RedisInstance();
await RedisInstance.instance.initialize();
}
logger.info(`🔁 Old Redis instance Called again :)`);
return RedisInstance.instance;
};
//Usable Function Component to get client
public getClient = async (): Promise<RedisClientType> => {
return RedisInstance.CacheClient;
};
}
现在您可以通过导出代码中的任何位置来使用该实例。就像下面这样:
import { RedisInstance } from "./redis";
export const example = async (): Promise<void> => {
const redisClient = await (await RedisInstance.getInstance()).getClient();
// Implement your logic with the client
};
每次调用 getInstance 时,它都会返回已创建的实例。 getClient 将帮助您获取使用凭据连接的客户端。