1. 程式人生 > >Redis cluster multi-key operation

Redis cluster multi-key operation

Redis叢集沒有使用一致性hash,而是引入了 雜湊槽(hash slot)的概念。

Redis叢集有16384(214)個雜湊槽,每個key通過CRC16校驗後對16384取模來決定放置哪個槽。叢集的每個節點負責一部分hash槽。HASH_SLOT = CRC16(key) mod 16384

Redis叢集的多鍵運算要求運算中的所有鍵都在一個槽中,否則會報 ERR CROSSSLOT Keys in request don't hash to the same slot 錯誤。

可以在鍵中使用雜湊標籤(hash tag)來解決這個問題,簡單的講就是使用花括號({})將key中的某部分字串括起來,這樣就會使用這部分字串計算取模分槽,就可以確保某些key被分配到一個槽中。

There is an exception for the computation of the hash slot that is used in order to implement hash tags. Hash tags are a way to ensure that multiple keys are allocated in the same hash slot. This is used in order to implement multi-key operations in Redis Cluster.

In order to implement hash tags, the hash slot for a key is computed in a slightly different way in certain conditions. If the key contains a “{…}” pattern only the substring between { and } is hashed in order to obtain the hash slot. However since it is possible that there are multiple occurrences of { or } the algorithm is well specified by the following rules:

  • IF the key contains a { character.
  • AND IF there is a } character to the right of {
  • AND IF there are one or more characters between the first occurrence of { and the first occurrence of }.

Then instead of hashing the key, only what is between the first occurrence of { and the following first occurrence of } is hashed.