Problem analysis
Exceptions are a redirection exception encountered when interacting with a Redis cluster using the Jedis client. This exception indicates that the client attempts to perform an operation on a Redis cluster node, but the data for this operation is not on that node, but on another node in the cluster. and
JedisMovedDataException
The difference is,JedisAskDataException
Usually occurs in operations involving multiple keys, where the data of one or more keys is located on a node outside the current node.
Reason for the error
In a Redis cluster, each key is hashed to a specific hash slot, and each hash slot is assigned to one or more Redis nodes. When the client tries to perform an operation involving multiple keys (such as MGET, MSET, etc.) and these keys are distributed on different hash slots, the operation fails and may triggerJedisAskDataException
Exception. Because Redis cluster requires that all keys belong to the same hash slot to perform these operations atomically on a node.
Solution
solveJedisAskDataException
The idea is to let the Jedis client automatically handle the redirect logic. useJedisCluster
Instead ofJedis
It is the correct way to deal with this situation, becauseJedisCluster
These redirects are processed internally and attempts to re-execute the operation on the correct node.
Solution
Method 1: Use JedisCluster instead of Jedis
When interacting with a Redis cluster, you should always useJedisCluster
Instead ofJedis
。JedisCluster
The hash slots and redirects will be processed automatically, and you don't need to care about these details.
Slide down to see the solution
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 { // Perform operations involving multiple keys, such as MGET List<String> values = ("key1", "key2", "key3"); // ...Perform other operations} finally { if (jedisCluster != null) { (); } }
In this example, evenkey1
、key2
andkey3
Distributed on different Redis nodes,JedisCluster
Redirection will also be processed automatically and executed on the correct nodeMGET
operate.
Method 2: Redesign your data model or operation (not recommended)
While operations involving multiple hash slots can be avoided by redesigning your data model or operations (i.e. storing relevant keys in the same hash slot), this is usually not a viable solution because it limits your data model and operational flexibility. Additionally, it can also cause data imbalance between hash slots, affecting the performance and reliability of Redis clusters. Therefore, this method is not generally recommended.
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!