我正在实现由Redis的Pub / Sub提供的signalR。
为了与Redis进行交互,我使用了StackExchange.Redis-1.2.6。
这里的问题是,当我在signalR集线器上订阅模式时,我会创建一个具有ConnectionId和我感兴趣的主题的组,并在Redis Pub / Sub上进行相同的操作。
当我收到消息时,我需要追溯并通知所有感兴趣的订户,但是问题是Redis不是给我匹配的模式,而是给我发布的主题。
这是代码示例:
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
ISubscriber sub = redis.GetSubscriber();
RedisChannel channelWithLiteral = new RedisChannel("messages", RedisChannel.PatternMode.Literal);
sub.Subscribe(channelWithLiteral, (channel, message) =>
{
Console.WriteLine($"Literal -> channel: '{channel}' message: '{message}'");
});
RedisChannel channelWithPattern = new RedisChannel("mess*", RedisChannel.PatternMode.Pattern);
sub.Subscribe(channelWithPattern, (channel, message) =>
{
Console.WriteLine($"Pattern -> channel: '{channel}' message: '{message}'");
});
sub.Publish("messages", "hello");
Console.ReadLine();
输出为:
我所期望的/需要的:
在https://redis.io/topics/pubsub上,它表示在使用PSUBSCRIBE时,我们会同时收到以下消息:原始主题和匹配的模式。
这是示例:
StackExchange.Redis是否有任何方法可以接收匹配的模式?
最佳答案
我已经在GitHub上发布了一个问题:RedisChannel is not retrieving the matched pattern when I receive the delegate:
您可以暂时看到一种解决方法。
“目前,唯一的方法就是在订阅时“捕获”订阅 channel 。”
这是解决方法:
将模式存储在代表Action临时引用上
变量
并与Redis一起传递该信息
channel
这是代码示例:
public class MyTest
{
private readonly ISubscriber subscriber;
public MyTest()
{
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
this.subscriber = redis.GetSubscriber();
}
public void SubscribeWithPattern(string pattern)
{
RedisChannel channelWithPattern = new RedisChannel(pattern, RedisChannel.PatternMode.Pattern);
string originalChannelSubcription = pattern;
this.subscriber.Subscribe(channelWithPattern, (channel, message) =>
{
Console.WriteLine($"OriginalChannelSubcription '{originalChannelSubcription}");
Console.WriteLine($"Channel: '{channel}");
Console.WriteLine($"Message: '{message}'");
});
}
public void Publish(string channel, string message)
{
this.subscriber.Publish(channel, message);
}
}