学海无涯

导航

Redis 用 IConnectionMultiplexer 连接 订阅消息

创建订阅类:

using StackExchange.Redis;

namespace TestWebApplication.BackgroundTasks
{
    /// <summary>
    /// Redis 订阅者,长时间运行的后台服务
    /// </summary>
    public class RedisSubscriber : BackgroundService
    {
        private readonly IConnectionMultiplexer m_Multiplexer;
        public RedisSubscriber(IConnectionMultiplexer multiplexer)
        {
            m_Multiplexer = multiplexer;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var subscribver = m_Multiplexer.GetSubscriber();
            return subscribver.SubscribeAsync("message", ((channel, value) =>
            {
                Console.WriteLine($"来自订阅的消息:{value}");
            }));
        }
    }
}

  注册后台服务:

 services.AddHostedService<RedisSubscriber>();//长时间运行的后台服务

  发布消息:

 

 

 

posted on 2022-09-18 09:51  宁静致远.  阅读(308)  评论(0编辑  收藏  举报