Tom
Tom

Reputation: 6332

How to use JedisCluster effectively

I am new to Redis and I am using Redis Java Client to work with Redis cluster.

I have following code:

public class HelloRedisCluster {
    public static void main(String[] args) {
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        nodes.add(new HostAndPort("127.0.0.1", 6001));
        nodes.add(new HostAndPort("127.0.0.1", 6002));
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10000);
        config.setMaxIdle(500);

        JedisCluster cluster = new JedisCluster(nodes);
        cluster.set("abc", "123");
        System.out.println(cluster.get("abc"));
        cluster.close();
    }
}

In the above code, it simply opens the cluster, set/get with Redis, and then close the cluster.

If the code is running as a service(eg in Servlet), then it will frequently open and close cluster, which would cause bad performance.

I would ask how to use JedisCluster effectively?

Thanks!

Upvotes: 1

Views: 10913

Answers (1)

Tom
Tom

Reputation: 6332

I have figured out the way that JedisCluster works. Internally, it has already used Jedis Pool.

The operations that JedisCluster provides follow the same pattern, take set for example:

1. Borrow a Jedis object from Jedis Pool
2. Call Jedis#set method
3. Release the Jedis object back to the pool.

So that, we can hold a JedisCluster instance in a Singleton object, and then close JedisCluster object when JVM exits, with following code:

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

public class JedisClusterUtil {
    private static JedisCluster cluster;

    static {
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        nodes.add(new HostAndPort("127.0.0.1", 6001));
        nodes.add(new HostAndPort("127.0.0.1", 6002));
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10000);
        config.setMaxIdle(500);

        cluster = new JedisCluster(nodes, config);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (cluster != null) {
                    cluster.close();
                }
            }
        });
    }

    public static JedisCluster getCluster() {
        return cluster;
    }
}

Upvotes: 8

Related Questions