如何让redis通知我的服务事件

ymzxtsji  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(261)

我有一台带redis的远程计算机。不时会向其中添加新条目(键值对)。我希望redis向我的c#服务发送关于此类事件的通知(我对value part感兴趣)。我在网上搜索了一下,找到了一个简单的代码示例来订阅我的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...
    }
}
wfypjpf4

wfypjpf41#

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

其工作原理如下:

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

相关问题