zoukankan      html  css  js  c++  java
  • Redis 发布/订阅模式

    一.命令简介

    1.PSUBSCRIBE 订阅一个或多个符合给定模式的频道。
    2.PUBLISH 将信息 message 发送到指定的频道 channel 。
    3.PUBSUB 是一个查看订阅与发布系统状态的内省命令, 它由数个不同格式的子命令组成
    4.PUNSUBSCRIBE 指示客户端退订所有给定模式。
    5.SUBSCRIBE 订阅给定的一个或多个频道的信息。
    6.UNSUBSCRIBE 指示客户端退订给定的频道。

    二.例子

    1.订阅msg

    2.发送信息

    三.代码实现

    using Newtonsoft.Json;
    using StackExchange.Redis;
    using System;
    
    namespace ResdisPubSub.PubSub
    {
        /// <summary>
        /// 通过redis实现的订阅-发布机制
        /// </summary>
        public class RedisSubscribe : ISubscribeService
        {
            //链接
            static ConnectionMultiplexer redis;
    
            static RedisSubscribe()
            {
                ConfigurationOptions config = new ConfigurationOptions()
                {
                    AbortOnConnectFail = false,
                    ConnectRetry = 10,
                    ConnectTimeout = 5000,
                    ResolveDns = true,
                    SyncTimeout = 5000,
                    EndPoints = { { "127.0.0.1:6379" } },
                    Password = "111111",
                    AllowAdmin = true,
                    KeepAlive = 180
                };
                redis = ConnectionMultiplexer.Connect(config);
            }
    
            /// <summary>
            /// 发布消息
            /// </summary>
            /// <typeparam name="T">消息类型</typeparam>
            /// <param name="channel">频道:消息的名称</param>
            /// <param name="msg">消息内容</param>
            /// <returns></returns>
            public void Publish<T>(string channel, T msg)
            {
                try
                {
                    if (redis != null && redis.IsConnected)
                    {
                        redis.GetSubscriber().Publish(channel, JsonConvert.SerializeObject(msg));
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("redis服务错误,详细信息:" + ex.Message + ",来源:" + ex.Source);
                }
       
            }
    
            /// <summary>
            /// 订阅消息
            /// </summary>
            /// <param name="subChannel">频道:消息的名称</param>
            /// <param name="action">收到消息后的处理</param>
            public void Subscribe(string subChannel, Action<string> action)
            {
                try
                {
                    if (redis != null && redis.IsConnected)
                    {
                        redis.GetSubscriber().Subscribe(subChannel, (channel, message) => { action(message); });
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("redis服务错误,详细信息:" + ex.Message + ",来源:" + ex.Source);
                }
    
            }
    
            /// <summary>
            /// 取消订阅
            /// </summary>
            /// <param name="channel">频道:消息的名称</param>
            public void Unsubscribe(string channel)
            {
                try
                {
                    if (redis != null && redis.IsConnected)
                    {
                        redis.GetSubscriber().Unsubscribe(channel);
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("redis服务错误,详细信息:" + ex.Message + ",来源:" + ex.Source);
                }
    
            }
    
            /// <summary>
            /// 取消全部订阅
            /// </summary>
            public void UnsubscribeAll()
            {
                try
                {
                    if (redis != null && redis.IsConnected)
                    {
                        redis.GetSubscriber().UnsubscribeAll();
                    }
                }
                catch (InvalidOperationException ex)
                {
                    Console.WriteLine("redis服务错误,详细信息:" + ex.Message + ",来源:" + ex.Source);
                }
       
            }
        }
    }
        class Program
        {
            static ISubscribeService client = new RedisSubscribe();
            static void Main(string[] args)
            {
                client.Subscribe("bigbigChannel", m => { Console.WriteLine($"我是bigbigChannel,接收到信息:{m}"); });
                Thread t = new Thread(Run);
                t.Start();
            }
    
            static void Run()
            {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(1000);
                    client.Publish("bigbigChannel", i.ToString());
                }
           
            }
        }

     源码下载:https://github.com/lgxlsm/ResdisPubSub

  • 相关阅读:
    对象结构型
    对象结构型
    对象行为型模式
    定时任务(二)
    定时任务(一)
    kill端口-更新sql-添加字段
    获取ip和端口号
    List集合中的末位元素置首位
    首页报表数据展示(一)
    具体的类中包括枚举类写法
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/7562944.html
Copyright © 2011-2022 走看看