Skip to content

Commit

Permalink
Fix django#273 -- Use consistent hashing for PubSub
Browse files Browse the repository at this point in the history
  • Loading branch information
raphaelm authored Sep 1, 2021
1 parent 49e419d commit ecb2d34
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions channels_redis/pubsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,19 @@ def __init__(

# For each host, we create a `RedisSingleShardConnection` to manage the connection to that host.
self._shards = [RedisSingleShardConnection(host, self) for host in hosts]

This comment has been minimized.

Copy link
@carltongibson

carltongibson Sep 2, 2021

Can you trim this please. Thanks.

def _get_shard(self, channel_or_group_name):
"""
Return the shard that is used exclusively for this channel or group.
"""
if len(self._shards) == 1:
# Avoid the overhead of hashing and modulo when it is unnecessary.
return self._shards[0]
shard_index = abs(hash(channel_or_group_name)) % len(self._shards)
return self._shards[shard_index]
if isinstance(channel_or_group_name, str):
channel_or_group_name = channel_or_group_name.encode("utf8")
bigval = binascii.crc32(channel_or_group_name) & 0xFFF
ring_divisor = 4096 / float(len(self._shards))
return self._shards[int(bigval / ring_divisor)]

def _get_group_channel_name(self, group):
"""
Expand Down

0 comments on commit ecb2d34

Please sign in to comment.