diff --git a/src/main/java/redis/clients/util/JedisClusterCRC16.java b/src/main/java/redis/clients/util/JedisClusterCRC16.java index c0d4afb..3c5c9b5 100644 --- a/src/main/java/redis/clients/util/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/util/JedisClusterCRC16.java @@ -3,8 +3,20 @@ package redis.clients.util; public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 static int crc; + public static int getSlot(String key) { + int s = key.indexOf("{"); + if (s > -1) { + int e = key.indexOf("}", s+1); + if (e > -1 && e != s+1) { + key = key.substring(s+1, e); + } + } + return getCRC16(key) % 16384; + } + + private static int getCRC16(String key) { crc = 0x0000; for (byte b : key.getBytes()) { for (int i = 0; i < 8; i++) { @@ -18,6 +30,6 @@ public class JedisClusterCRC16 { } } - return crc &= 0xffff % 16384; + return crc &= 0xffff ; } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 356e642..ff8a38f 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -170,6 +170,14 @@ public class JedisClusterTest extends Assert { node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); jc.set("51", "foo"); } + + @Test + public void testRedisHashtag() { + assertEquals(JedisClusterCRC16.getSlot("{bar"), JedisClusterCRC16.getSlot("foo{{bar}}zap")); + assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), JedisClusterCRC16.getSlot("{user1000}.followers")); + assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar")); + assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); + } private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { @@ -191,5 +199,5 @@ public class JedisClusterTest extends Assert { Thread.sleep(50); } } - + }