Java Redis Cluster Connection

In Java, connecting to a Redis cluster can be achieved using the JedisCluster class. This class is provided by the Jedis client library for connecting to a Redis cluster.

Here is a simple example code demonstrating how to connect to a Redis cluster.

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

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

public class RedisClusterExample {

    public static void main(String[] args) {
        Set<HostAndPort> jedisClusterNodes = new HashSet<>();
        jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7000));
        jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7001));
        jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7002));

        JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes);

        jedisCluster.set("foo", "bar");
        String value = jedisCluster.get("foo");
        System.out.println(value);

        jedisCluster.close();
    }
}

In the code above, a Set object containing information about Redis cluster nodes is first created, and then a JedisCluster object is created using this node information. Subsequently, the JedisCluster object can be used to perform various Redis operations, such as setting and retrieving values. Finally, it is necessary to call the close() method to close the JedisCluster object.

bannerAds