A Redis cluster client that manages multiple Redis instances and handles cluster operations.
Definitionsdef initialize(endpoints, **options)
Create a new instance of the cluster client.
Implementationdef initialize(endpoints, **options)
@endpoints = endpoints
@options = options
@shards = nil
end
def clients_for(*keys, role: :master, attempts: 3)
Execute a block with clients for the given keys, grouped by cluster slot.
Signaturekeys
Array
The keys to find clients for.
role
Symbol
The role of nodes to use (:master or :slave).
attempts
Integer
Number of retry attempts for cluster errors.
{|client, keys| ...}
Block called for each client-keys pair.
client
Client
The Redis client for the slot.
keys
Array
The keys handled by this client.
def clients_for(*keys, role: :master, attempts: 3)
slots = slots_for(keys)
slots.each do |slot, keys|
yield client_for(slot, role), keys
end
rescue ServerError => error
Console.warn(self, error)
if error.message =~ /MOVED|ASK/
reload_cluster!
attempts -= 1
retry if attempts > 0
raise
else
raise
end
end
def client_for(slot, role = :master)
Get a client for a specific slot.
Signatureslot
Integer
The cluster slot number.
role
Symbol
The role of node to get (:master or :slave).
Client
The Redis client for the slot.
def client_for(slot, role = :master)
unless @shards
reload_cluster!
end
if nodes = @shards.find(slot)
nodes = nodes.select{|node| node.role == role}
else
raise SlotError, "No nodes found for slot #{slot}"
end
if node = nodes.sample
return (node.client ||= Client.new(node.endpoint, **@options))
end
end
def crc16(bytes)
This is the CRC16 algorithm used by Redis Cluster to hash keys. Copied from https://github.com/antirez/redis-rb-cluster/blob/master/crc16.rb
Implementationdef crc16(bytes)
sum = 0
bytes.each_byte do |byte|
sum = ((sum << 8) & 0xffff) ^ XMODEM_CRC16_LOOKUP[((sum >> 8) ^ byte) & 0xff]
end
return sum
end
def slot_for(key)
Return Redis::Client for a given key. Modified from https://github.com/antirez/redis-rb-cluster/blob/master/cluster.rb#L104-L117
Implementationdef slot_for(key)
key = key.to_s
if s = key.index("{")
if e = key.index("}", s + 1) and e != s + 1
key = key[s + 1..e - 1]
end
end
return crc16(key) % HASH_SLOTS
end
def slots_for(keys)
Calculate the hash slots for multiple keys.
Signaturekeys
Array
The keys to calculate slots for.
Hash
A hash mapping slot numbers to arrays of keys.
def slots_for(keys)
slots = Hash.new{|hash, key| hash[key] = []}
keys.each do |key|
slots[slot_for(key)] << key
end
return slots
end
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4