Desidero utilizzare operazioni multi-chiave su un cluster autoprogettato Amazon ElastiCache (Redis OSS) con modalità cluster attivata. Tuttavia, ricevo l'errore “CROSSSLOT Keys in request don’t hash to the same slot“.
Breve descrizione
Ricevi il seguente errore quando le chiavi non si trovano nello stesso slot hash, anche se sono archiviate nello stesso nodo:
"CROSSSLOT Keys in request don't hash to the same slot"
Per implementare operazioni multi-chiave in un cluster ElastiCache (Redis OSS) con shard e modalità cluster attivata, esegui l'hash delle chiavi nello stesso slot hash.
Nei seguenti esempi di set, "myset2" e "myset" si trovano nello stesso nodo:
172.31.62.135:6379> scan 0
1) "0"
2) 1) "myset"
2) "myset2"
Tuttavia, un'operazione multi-chiave non è supportata:
172.31.62.135:6379> SUNION myset myset2(error) CROSSSLOT Keys in request don't hash to the same slot
L'operazione non è supportata perché le chiavi non si trovano nello stesso slot hash. I due set si trovano in due slot diversi, 560 e 7967:
172.31.62.135:6379> CLUSTER KEYSLOT myset(integer) 560
172.31.62.135:6379> CLUSTER KEYSLOT myset2(integer) 7967
Risoluzione
Metodo 1
Puoi utilizzare una libreria client Redis che fornisce supporto per i cluster Redis con modalità cluster attivata. Per ulteriori informazioni, consulta Redis cluster specification (Specifica del cluster Redis) sul sito web Redis.
L'esempio seguente utilizza redis-cli per ottenere chiavi da slot che si trovano in shard diversi. Il risultato è un errore CROSSSLOT:
redis-cli -c -h RedisclusterCfgEndpointRedisclusterCfgEndpoint:6379> mget key1 key2
(error) CROSSSLOT Keys in request don't hash to the same slot
Se invece utilizzi redis-py-cluster per ottenere chiavi da slot che si trovano in shard diversi, ricevi l'output corretto:
>>> from rediscluster import RedisCluster>>> startup_nodes = [{"host": "RedisclusterCfgEndpoint", "port": "6379"}]
>>> rc = RedisCluster(startup_nodes=startup_nodes, decode_responses=True,skip_full_coverage_check=True)
>>> print(rc.mget("key1","key2"))
Metodo 2
Quando crei chiavi per operazioni multi-chiave su un cluster con modalità cluster attivata, forza le chiavi nello stesso slot hash. Puoi utilizzare hashtag per forzare le chiavi nello stesso slot hash. Quando la chiave contiene una sequenza {...}, solo la sottostringa tra parentesi graffe, { e }, viene sottoposta ad hashing per calcolare lo slot hash.
Di seguito è riportato un esempio di più set con hashing nello stesso slot hash. Le chiavi {user1}:myset e {user1}:myset2 vengono sottoposte a hashing nello stesso slot hash. Solo user1 viene utilizzato per calcolare lo slot hash.
172.31.62.135:6379> CLUSTER KEYSLOT {user1}:myset(integer) 8106
172.31.62.135:6379> CLUSTER KEYSLOT {user1}:myset2
(integer) 8106
172.31.62.135:6379> SUNION {user1}:myset {user1}:myset2
1) "some data for myset"
2) "some data for myset2"
Dopo aver eseguito l'hashing di entrambi i set nello stesso slot hash, è possibile eseguire un'operazione multi-chiave.