Fal*_*ppy 1 c# publish-subscribe redis
我有一台带有 Redis 的远程计算机。不时向其中添加新条目(键值对)。我希望 Redis 向我的 C# 服务发送有关此类事件的通知(我对价值部分感兴趣)。我在网上搜索并找到了简单的代码示例来将我的服务订阅到 Redis。如何让Redis发送通知?
服务:
public partial class ResultsService : ServiceBase
{
private ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConnection"]);
private const string ChatChannel = "__keyspace@0__:*";
public VerificationResultsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Start();
}
public void Start()
{
var pubsub = connection.GetSubscriber();
pubsub.Subscribe(ChatChannel, (channel, message) => MessageAction(message));
while (true)
{
}
}
private static void MessageAction(RedisValue message)
{
// some handler...
}
}
Run Code Online (Sandbox Code Playgroud)
使redis发送自动keyspace通知是一个redis服务器配置块,可以通过.conf文件( notify-keyspace-events)或者CONFIG SET在运行时启用;相关文档在这里。
您可以通过示例代码看到它是如何工作的:
using StackExchange.Redis;
using System;
using System.Linq;
static class P
{
private const string ChatChannel = "__keyspace@0__:*";
static void Main()
{
// connect (allowAdmin just lets me use ConfigSet)
using var muxer = ConnectionMultiplexer.Connect("127.0.0.1,allowAdmin=true");
// turn on all notifications; note that this is server-wide
// and is NOT just specific to our connection/code
muxer.GetServer(muxer.GetEndPoints().Single())
.ConfigSet("notify-keyspace-events", "KEA"); // KEA=everything
// subscribe to the event
muxer.GetSubscriber().Subscribe(ChatChannel,
(channel, message) => Console.WriteLine($"received {message} on {channel}"));
// stop the client from exiting
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
其工作原理如下:
但是,在许多情况下,您可能会发现这太“嘈杂”,您可能更喜欢使用您在执行需要通知的事情时手动发布的自定义命名事件,或者(再次手动)您可以使用流特征来消费数据流(流可以被视为“发生的事情”意义上的事件流,但它们不是通过发布/订阅传递的)。