Is there a way to make a specific key locate on a specific redis instance in cluster mode?

柔情痞子 提交于 2020-02-04 02:51:10

问题


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:

  1. A map of what shard or slot-range resides in which redis instance.

  2. 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:

  1. Look at the slot map and take the slot ranges that reside on that node.

  2. Select a slot within that node's range.

  3. Look in the sharding table for the entry of that slot.

  4. Slap that string with curly braces on the key. e.g. convert foo to foo{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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!