node-redis icon indicating copy to clipboard operation
node-redis copied to clipboard

Getting the ClientClosedError when using quit() / disconnect() methods

Open peterdee opened this issue 5 years ago • 20 comments

Hi. I've noticed that calling the quit() or disconnect() methods throws the following error:

ClientClosedError: The client is closed
    at RedisSocket.disconnect (/Users/peter/Playground/test-redis/node_modules/@node-redis/client/dist/lib/client/socket.js:62:19)
    at Commander.disconnect (/Users/peter/Playground/test-redis/node_modules/@node-redis/client/dist/lib/client/index.js:279:64)
    at stop (/Users/peter/Playground/test-redis/index.js:6:16)
    at Object.<anonymous> (/Users/peter/Playground/test-redis/index.js:9:1)

I am running the following script:

const redis = require('redis');

const client = redis.createClient();

async function stop() {
  await client.disconnect();
}

stop();

I am using:

  • Node 16.2
  • redis-server 5.0.7
  • node-redis 4.0.0
  • Mac OS Monterey 12.0.1

I am not sure if this behaviour is valid, since it prevents me from shutting down the connection gracefully.

I did not have this problem previously when using the 3.1.2 version of node-redis.

peterdee avatar Dec 02 '21 09:12 peterdee

I've upgraded my redis-server to version 6.2.6, but it did not help.

peterdee avatar Dec 02 '21 09:12 peterdee

I've also checked the client.isOpen property. It equals to false after connection is created:

const redis = require('redis');

async function run() {
  const client = redis.createClient();

  console.log(client.isOpen); // this is false

  await client.disconnect();
}

run();

This explains why the error is thrown when using the quit() method:

    async quit(fn: () => Promise<unknown>): Promise<void> {
        if (!this.#isOpen) {
            throw new ClientClosedError(); // this is the thrown error
        }

        this.#isOpen = false;
        await fn();
        this.disconnect();
    }

I am not sure about the disconnect() though, because it checks the existing socket connection. Connection itself is stored as a private property and I cannot access it.

peterdee avatar Dec 02 '21 10:12 peterdee

You should call .quit/.disconnect only after you have called .connect

const redis = require('redis');

async function run() {
  const client = redis.createClient();

  await client.connect();

  console.log(client.isOpen); // this is true

  await client.disconnect();
}

run();

leibale avatar Dec 02 '21 15:12 leibale

@leibale Thank you, it works as expected now.

I thought that createClient() will create connection without the explicit connect() call.

peterdee avatar Dec 03 '21 06:12 peterdee

That changed in V4

jeroen-hoekstra avatar Dec 10 '21 07:12 jeroen-hoekstra

Hi

With the newly introduced, explicit connect() method and having used Promises, how do we use the Redis connection in scenario, where there are multiple node modules/files

Eg: src/module_foo/foo.js // sets a value for a key in redis src/module_foo/bar.js // gets a value from redis for a key

How is this scenario supported? none of the example try to show this

rajiff avatar Dec 21 '21 06:12 rajiff

@rajiff I don't understand what is your issue exactly. You can store Redis connection in a singleton instance and reuse it in several modules.

Here's a very simple example of Redis connection:

// redis-connection.js
import redis from 'redis';

class RedisClient {
  constructor() {
    this.Client = null;
  }

  async connect({ host, port, password }) {
    this.Client = redis.createClient({ host, port, password });
    await this.Client.connect();
    return this.Client;
  }
}

export default new RedisClient();

Create connection somewhere in your application during your application launch:

// launcher.js
import connection from './redis-connection.js';

async function launch() {
  await connection.connect({ host, port, password });
}

launch();

You can then access the connected client from other modules:

// write-value.js
import connection from './redis-connection.js';

async function storeValue() {
  await connection.Client.set('key', 'value');
}

storeValue();
// read-value.js
import connection from './redis-connection.js';

async function readValue() {
  const key = await connection.Client.get('key');
  console.log(key);
}

readValue();

peterdee avatar Dec 21 '21 11:12 peterdee

Here, there is a Hello World sample that works with

node -v => v16.13.0 npm -v => 8.3.0 redis-cli -v => redis-cli 6.0.15

import { createClient } from 'redis';

const bootstrap = async () => {
  const client = createClient();

  await client.connect();
  await client.set('hello', 'world!');

  const key1Val = await client.get('hello');

  console.log(key1Val);
};

bootstrap();

siyavashhamdi avatar Dec 21 '21 20:12 siyavashhamdi

Hey @siyavashhamdi thanks for posting it

Yes that should work, after posting question here, I did below and it worked for me, was about to update here too

const redis = require('redis');

async function createRedisClient () {
  const client = redis.createClient();

  client.on('connect', () => console.log('Connected to REDIS!'));
  client.on('error', (err) => console.log('Error connecting to REDIS: ', err));

  await client.connect();

  return client;
}

module.exports = createRedisClient();

and to use it

const redisClient = require("./reidsClient");

redisClient.then((client) => { 
  // do something with the client
  await client.set("Hello", "Await World");
  // this also works, if we don't want to use await
  client.set("Hello", "Real World").then(()=> { 
     // can do something here 
  });
});

rajiff avatar Dec 21 '21 23:12 rajiff

@peterdee if you see the code example you provided, every method is a async method, that is the issue I am pointing, as not every one like to use async/await as it hides true parallelism that JS offers can cause code readability issue in understanding parallelism

However, I have got a work around, I wish there was a way without using async/await as node-redid is really an awesome library

Thanks for responding, sorry if I sounded arrogant

Will try to make this sample as part of Doc later

rajiff avatar Dec 21 '21 23:12 rajiff

@rajiff I don't understand what is your issue exactly. You can store Redis connection in a singleton instance and reuse it in several modules.

Here's a very simple example of Redis connection:

// redis-connection.js
import redis from 'redis';

class RedisClient {
  constructor() {
    this.Client = null;
  }

  async connect({ host, port, password }) {
    this.Client = redis.createClient({ host, port, password });
    await this.Client.connect();
    return this.Client;
  }
}

export default new RedisClient();

Create connection somewhere in your application during your application launch:

// launcher.js
import connection from './redis-connection.js';

async function launch() {
  await connection.connect({ host, port, password });
}

launch();

You can then access the connected client from other modules:

// write-value.js
import connection from './redis-connection.js';

async function storeValue() {
  await connection.Client.set('key', 'value');
}

storeValue();
// read-value.js
import connection from './redis-connection.js';

async function readValue() {
  const key = await connection.Client.get('key');
  console.log(key);
}

readValue();

This helps me to create connection ,set and get keys from redis 6.2.6

yanxel18 avatar Jan 14 '22 06:01 yanxel18

Here's my version of Redis connection. No need to call Client every time.

  1. Define Redis instance
// redisClient.js
const redis = require('redis');
const { redisConfig } = require('./config/redis');

class RedisClient {
    constructor() {
        if (!RedisClient.instance) {
            this.client = redis.createClient(redisConfig);
            RedisClient.instance = this;
        }
        return RedisClient.instance.client;
    }

    async connect() {
        // error handling
        this.client.on('error', console.error);
        await this.client.connect();
    }
}

module.exports = new RedisClient();
  1. Create connection at entry point of the app.
// index.js
const redisClient = require('./redisClient');

(async () => {
    await redisClient.connect();
})();
  1. Use case
const redisClient = require('./redisClient');

const geData = async () => {
    return await redisClient.GET('test');
};

ParkerOu avatar Aug 30 '23 11:08 ParkerOu

ununtu server 20.04 Error: The client is closed at Commander._RedisClient_sendCommand (/home/major/pool/node_modules/@redis/client/dist/lib/client/index.js:493:31) at Commander.commandsExecutor (/home/major/pool/node_modules/@redis/client/dist/lib/client/index.js:188:154) at BaseClass. [as info] (/home/major/pool/node_modules/@redis/client/dist/lib/commander.js:8:29) at checkRedisVersion (/home/major/pool/init.js:147:15)

I'm so tired I can't find the mistake :(

domajor avatar Sep 11 '23 09:09 domajor

ununtu server 20.04 Error: The client is closed

Do your redis client connect() first?

ParkerOu avatar Sep 11 '23 09:09 ParkerOu

yess

domajor avatar Sep 11 '23 11:09 domajor

yess

Show your code that we could help.

ParkerOu avatar Sep 11 '23 12:09 ParkerOu

~/pool$ redis-cli 127.0.0.1:6379> ping PONG 127.0.0.1:6379> set test "It's working! Invalid argument(s) 127.0.0.1:6379> get test (nil) :(((

domajor avatar Sep 11 '23 16:09 domajor

This’s not this package issue. Check redis docs and try with redis playground. https://redis.io/commands/set/

Your set command lack of Quotation mark (”)

ParkerOu avatar Sep 11 '23 16:09 ParkerOu

l$ redis-cli 127.0.0.1:6379> ping PONG 127.0.0.1:6379> set test "It's working!" OK 127.0.0.1:6379> get test "It's working!" 127.0.0.1:6379> exit Error: The client is closed at Commander._RedisClient_sendCommand :/ :/ :/

domajor avatar Sep 11 '23 16:09 domajor

classPrivateFieldGet(this, _RedisClient_instances, "m", _RedisClient_sendCommand).call(this, ['PING']) .then(reply => this.emit('ping-interval', reply)) .catch(err => this.emit('error', err)) .finally(() => __classPrivateFieldGet(this, _RedisClient_instances, "m", _RedisClient_setPingTimer).call(this)); }, __classPrivateFieldGet(this, _RedisClient_options, "f").pingInterval), "f"); }, _RedisClient_sendCommand = function _RedisClient_sendCommand(args, options) { if (!__classPrivateFieldGet(this, _RedisClient_socket, "f").isOpen) { return Promise.reject(new errors_1.ClientClosedError());

domajor avatar Sep 11 '23 16:09 domajor