Repository navigation
Description
IConnectionMultiplexer.HashSlot(RedisKey) tells you which hash slot a key is in, but there's no public way to ask the same for a RedisChannel. With sharded pub/sub, that's a natural thing to want. For example, to tell whether a HashSlotMoved event concerns a channel you're subscribed to, you compare e.HashSlot against the channel's slot.
The workaround, and where it goes wrong
The obvious workaround is to hash the channel's name as if it were a key:
var slot = multiplexer.HashSlot(new RedisKey(channel)); // or (RedisKey)(byte[])channel!The repo's own ClusterShardedTests does this too. But it isn't what the library actually routes by, which is ServerSelectionStrategy.HashSlot(in RedisChannel). That method is internal. It differs from the workaround in two ways:
ConfigurationOptions.ChannelPrefix. For a channel that doesn't ignore the prefix (e.g.RedisChannel.Sharded(...)), the slot is computed from the prefixed name, since that's the name sent to the server. The workaround hashes the bare name, so with a prefix configured it gets a different slot. It does so silently.- Key-routed keyspace channels. A channel from
RedisChannel.KeySpaceSingleKey(key, db)is routed by the key part (RoutingSpanstrips the__keyspace@{db}__:prefix). The workaround hashes the whole channel name instead.
Proposal
Expose the existing logic, alongside the key overload:
public interface IConnectionMultiplexer
{
int HashSlot(RedisKey key);
int HashSlot(RedisChannel channel); // new
}
// ConnectionMultiplexer
public int HashSlot(RedisChannel channel) => ServerSelectionStrategy.HashSlot(channel);Like HashSlot(RedisKey), it would return -1 when not connected to a cluster.
This adds a member to a public interface. I believe that's been acceptable in minor releases before, since the interface isn't meant to be implemented outside the library. It's flagged here in case you'd prefer a different shape, e.g. an extension method or a member on ISubscriber.
I have a PR ready that does this, with unit tests against the in-process cluster server.
Activity
Expose HashSlot(RedisChannel) on IConnectionMultiplexer
Expose `HashSlot(RedisChannel)` on `IConnectionMultiplexer` (seredis#…
v4: absorb main 3.5.0, part 2 - pub/sub: channel hash slot, publish r…