SoFunction
Updated on 2025-03-06

Exception resolution

Problem analysis

The exception occurs when using the Jedis client to interact with the Redis cluster. This exception usually indicates that the client attempts to access a key, but this key is not on the node the client initially tries to connect to, but is redirected to another node by the Redis cluster.

Reason for the error

In a Redis cluster, keys are distributed to different nodes through a hash slot. Each key is mapped to a specific hash slot via the CRC16 checksum function, which is associated with one or more nodes in the Redis cluster. When the client tries to access a key, if the node it connects to does not contain the hash slot of the key, the node returns a redirection instruction telling the client which node to search for the key.

JedisMovedDataExceptionThe exception is thrown in this case. It tells the client that the key it is trying to access has been moved to another node in the cluster.

Solution

The idea to solve this exception is to enable the Jedis client to automatically handle redirect instructions of the Redis cluster. Jedis provides native support for Redis clusters throughJedisClusterClass, it can automatically handle redirection between nodes.

Solution

Method 1: Use JedisCluster instead of Jedis

When you interact with a Redis cluster, you should useJedisClusterInstead ofJedisJedisClusterThe hash slots and redirects will be processed automatically, and you don't need to care about these details.

Code Example

Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
(new HostAndPort("127.0.0.1", 7000));
(new HostAndPort("127.0.0.1", 7001));
// ... Add other nodes
JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes);

try {
    String value = ("mykey");
    // ...Perform other operations} finally {
    if (jedisCluster != null) {
        ();
    }
}

Method 2: Handle redirection (not recommended)

Although it can be captured manuallyJedisMovedDataExceptionException and reconnect to the correct node based on the information in the exception, but this approach is usually not recommended because it increases the complexity of the code and the possibility of errors. The Jedis client library should be allowed to handle these details as much as possible.

Summarize

When interacting with a Redis cluster, you should useJedisClusterLet's replaceJedis, so that hash slots and redirects are processed automatically. This simplifies your code and reduces the possibility of errors.

This is all about this article about exception resolution. For more related content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!