gpt4 book ai didi

c# - 如何让 Redis 通知我的服务有关事件

转载 作者:行者123 更新时间:2023-12-03 06:41:22 24 4
gpt4 key购买 nike

我有一台带有 Redis 的远程计算机。不时向其中添加新条目(键值对)。我希望 Redis 向我的 C# 服务发送有关此类事件的通知(我对值(value)部分感兴趣)。我在网上搜索并找到了将我的服务订阅到 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 启用在运行时; is here 的文档.

您可以使用示例代码查看它是如何工作的:

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();
}
}

它的工作原理如下:

enter image description here

但是,在许多情况下,您可能会发现这太“嘈杂”,您可能更喜欢使用自定义命名事件,当您执行需要通知的事情时手动发布,或者(再次手动)您可以使用 streams使用数据流的功能(流可以被视为“发生的事情”意义上的事件流,但它们不是通过 pub/sub 传递的)。

关于c# - 如何让 Redis 通知我的服务有关事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60772752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com