问题
I want to make my multi-locks locate on different redis instances.
I find out that redission can specify an instance to execute command on, but if the command is key-related, the instance specified will transmit the command to another instance.
Can you give me some advice?
回答1:
You can, but it's not trivial. First of all, Redis uses curly braces in the key to determine the sharding part of it, so you can decide to modify a key and send it to an arbitrary shard.
Now, you need two things:
A map of what shard or slot-range resides in which redis instance.
A way to know which string maps to which slot, so you can force a "sharding string" on your key to route it to a specific shard.
The first one is easy - CLUSTER SLOTS
will give you that map, just parse it.
The second one is more tricky - but luckily I've done this work already. I have created a table of the shortest possible alphanumeric string mapping to each of the 16384 slots in Redis cluster. I'ts in C but you can easily convert it to whatever. https://gist.github.com/dvirsky/93f43277317f629bb06e858946416f7e
So your algorithm would be, given a key and a desired node:
Look at the slot map and take the slot ranges that reside on that node.
Select a slot within that node's range.
Look in the sharding table for the entry of that slot.
Slap that string with curly braces on the key. e.g. convert
foo
tofoo{e4x}
.
And that's it! Any command using this key will be routed to that shard.
Pseudo-python version of it:
# Build this table from CLUSTER SLOTS or CLUSTER NODES
slots = {
'127.0.0.1:7000': [(0, 1045),(2000,2100)]
...
}
# Build this table from the C example:
sharding_table = ["06S", "Qi", "5L5", "4Iu", "4gY", ....]
def retarget_key(key, node):
ranges = slots[node]
sharding_key = shading_table[ranges[0][0]]
return '%s{%s}' % (key, sharding_key)
来源:https://stackoverflow.com/questions/46294925/is-there-a-way-to-make-a-specific-key-locate-on-a-specific-redis-instance-in-clu