我有一台装有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...
}
}
使redis发送自动的密钥空间通知是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();
}
}
它的工作原理如下:
但是,在许多情况下,您可能会发现这太“嘈杂”,您可能更喜欢使用在执行需要通知的操作时手动发布的自定义命名事件,或者(再次手动)使用流功能消耗数据流(可以将流视为“发生的事情”,但不通过pub / sub传递)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句