最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - redis connection + singleton + node.js - Stack Overflow

programmeradmin1浏览0评论

I am using redis to store sessions in my project.

In 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');
});

In my routes.js files i have to get all information from redis, so i am using the following:

var client = redis.createClient();

client.on('error', function(err){
  console.log('Something went wrong ', err)
});

But everytime its connecting to redis. How can i connect redis once in my app.js and use it everywhere. please suggest ideas. Thanks in advance.

EDIT

app.js

module.exports.client = client;

routes.js

var client = require("../app.js").client;
client.hgetall();

But i am receiving error

TypeError: Cannot read property 'hgetall' of undefined

I am using redis to store sessions in my project.

In 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');
});

In my routes.js files i have to get all information from redis, so i am using the following:

var client = redis.createClient();

client.on('error', function(err){
  console.log('Something went wrong ', err)
});

But everytime its connecting to redis. How can i connect redis once in my app.js and use it everywhere. please suggest ideas. Thanks in advance.

EDIT

app.js

module.exports.client = client;

routes.js

var client = require("../app.js").client;
client.hgetall();

But i am receiving error

TypeError: Cannot read property 'hgetall' of undefined
Share Improve this question edited May 16, 2018 at 6:44 Subburaj asked May 16, 2018 at 6:29 SubburajSubburaj 5,20211 gold badges47 silver badges95 bronze badges 8
  • export the client from app.js.. then import the client into routes.js – Ritwick Dey Commented May 16, 2018 at 6:34
  • @Ritwick Dey thanks, could you please provide some examples – Subburaj Commented May 16, 2018 at 6:35
  • Sorry. I though it is a client application. – Ritwick Dey Commented May 16, 2018 at 6:42
  • You have to manage session in that case – Ritwick Dey Commented May 16, 2018 at 6:42
  • @Ritwick Dey Please see my edited post – Subburaj Commented May 16, 2018 at 6:44
 |  Show 3 more ments

3 Answers 3

Reset to default 2

In 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 }

In routes.js

var { client } = require('./app');

client.on('error', function(err){
  console.log('Something went wrong ', err)
});

(Assuming app.js and routes.js are in same level of directory)

EDIT: fixed few typo

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);
});

I hope this will resolve your issue. Thanks

A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. In object-oriented programming, it is a design pattern. The code snippets below can be considered an attempt to implement a singleton class in 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("
发布评论

评论列表(0)

  1. 暂无评论