Search code examples
redisjedis

What is the recommended way to close connection to Redis?


I use jedis to connect to Redis server. As part of clean up, I want to close the connections. I see that there are 4 different ways as listed below. Can some one help me understand the difference/redundancy and recommend when to use what ?

1. jedis.disconnect();
2. jedis.close();
3. jedis.quit();
4. jedis.configSet("timeout",30);

NOTE: I use AWS ElastiCache , which disables editing the config and hence jedis.configSet("timeout",30); is not an option.

I am using Jedis version 3.6 , Below is my code to establish connection to Redis via Jedis

    final URI uri = URI.create(System.getenv("REDIS_CLUSTER_URI"));
    final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    // These SSL parameters ensure that we use the same hostname verifier used
    // for HTTPS.
    final SSLParameters sslParameters = new SSLParameters();
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    /*sslParameters.setWantClientAuth(true);
    sslParameters.setNeedClientAuth(true);*/

    jedis = new Jedis(uri,sslSocketFactory,sslParameters,null);
    // Pass the AUTH Token (Password)
    jedis.auth(System.getenv("REDIS_AUTH_TOKEN"));

Solution

  • First of all, why not use a more recent version of Jedis?


    1. jedis.disconnect(); - Used to be same as jedis.close();. As close() is now universally recognized one, it is better to use that.

    2. jedis.close(); - Should handle releasing resources properly.

      Note for other users: If Jedis object is part of a pool, close() only returns the respective object back to the pool and does not release the underlying resources.

    3. jedis.quit(); - close() releases resources only from application (JVM) side. It does not do anything in server (Redis) side. quit() asks the server to close the connection. But this requires one extra round trip. You may choose to do it if you want.

      Note: It also releases the resources internally. So a close() after quit() is not necessary.

    4. jedis.configSet("timeout", ...); - This is for idle connection management only from server side. Even if you are not using AWS ElastiCache, this should not be your resource management solution.

      Note: This can be a part of resource management.