Ver Fonte

Add support for key hash tags in redis-cluster (Redis 3.0.0b1).

Multi-keys operations are not allowed even when keys generate the same
hash but this will probably be supported in later betas of Redis which
means we will basically end up reusing the whole strategy used for
client-side sharding.
Daniele Alessandri há 11 anos atrás
pai
commit
ba2ffb612a

+ 2 - 0
CHANGELOG.md

@@ -3,6 +3,8 @@ v0.8.6 (2014-xx-xx)
 
 - Minor tweaks to make this version of Predis compatible with HHVM >= 2.4.0.
 
+- Add support for key hash tags when using redis-cluster (Redis 3.0.0b1).
+
 
 v0.8.5 (2014-01-16)
 ================================================================================

+ 22 - 1
lib/Predis/Cluster/RedisClusterHashStrategy.php

@@ -287,6 +287,27 @@ class RedisClusterHashStrategy implements CommandHashStrategyInterface
      */
     public function getKeyHash($key)
     {
-        return $this->hashGenerator->hash($key);
+        $key = $this->extractKeyTag($key);
+        $hash = $this->hashGenerator->hash($key);
+
+        return $hash;
+    }
+
+    /**
+     * Returns only the hashable part of a key (delimited by "{...}"), or the
+     * whole key if a key tag is not found in the string.
+     *
+     * @param  string $key A key.
+     * @return string
+     */
+    protected function extractKeyTag($key)
+    {
+        if (false !== $start = strpos($key, '{')) {
+            if (false !== $end = strpos($key, '}', $start)) {
+                $key = substr($key, ++$start, $end - $start);
+            }
+        }
+
+        return $key;
     }
 }

+ 5 - 5
tests/Predis/Cluster/RedisClusterHashStrategyTest.php

@@ -22,14 +22,14 @@ class RedisClusterHashStrategyTest extends PredisTestCase
     /**
      * @group disconnected
      */
-    public function testDoesNotSupportKeyTags()
+    public function testSupportsKeyTags()
     {
         $strategy = $this->getHashStrategy();
 
-        $this->assertSame(35910, $strategy->getKeyHash('{foo}'));
-        $this->assertSame(60032, $strategy->getKeyHash('{foo}:bar'));
-        $this->assertSame(27528, $strategy->getKeyHash('{foo}:baz'));
-        $this->assertSame(34064, $strategy->getKeyHash('bar:{foo}:bar'));
+        $this->assertSame(44950, $strategy->getKeyHash('{foo}'));
+        $this->assertSame(44950, $strategy->getKeyHash('{foo}:bar'));
+        $this->assertSame(44950, $strategy->getKeyHash('{foo}:baz'));
+        $this->assertSame(44950, $strategy->getKeyHash('bar:{foo}:bar'));
     }
 
     /**