• c# 使用StackExchange.Redis 发布订阅功能


    c# 使用StackExchange.Redis 发布订阅功能

    业务场景

    举个例子:业务系统触发短信发送申请,但短信发送模块速度跟不上,需要将来不及处理的消息暂存一下,缓冲压力 

    发布示例

                for (var i = 1; i < 20; i++) {
     
                    Redis.Using(rd => { rd.Use(1).RedisPub<string>("redis_20190605_pay", "pay amt=" + i); });
     
                    Thread.Sleep(200);
     
                }
     

    订阅示例

            private static Redis redis;
     
            static void Main(string[] args) {
     
                redis = new Redis();
                redis.RedisSubMessageEvent += RedisSubMessageEvent;
                redis.Use(1).RedisSub("redis_20190605_pay");
     
                Console.ReadKey();
     
           }
     
            private static void RedisSubMessageEvent(string msg) {
     
                Console.Write($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} RedisSubMessageEvent: {msg}");
            }
     

    效果图

    StackExchange.Redis封装的类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using StackExchange.Redis;
     
    namespace Utils.Framework {
     
        public class Redis : IDisposable {
     
            private static ConnectionMultiplexer redis = null;
            private static bool connected = false;
            private IDatabase db = null;
            private int current = 0;
            public static bool IsConnected { get { Open(); return redis.IsConnected; } }
            public static bool Test() {
                bool r = true;
                try {
                    Redis.Using(rs => { rs.Use(0); });
                } catch (Exception e) {
                    Log.Logs("[Redis] test fail " + e.Message);
                    r = false;
                }
                if (r) Log.Logs("[Redis] test ok.");
                return r;
            }
            private static int Open() {
                if (connected) return 1;
                redis = ConnectionMultiplexer.Connect("localhost:6379,password=123456,abortConnect = false");
                connected = true;
                return 1;
            }
            public static void Using(Action<Redis> a) {
                using (var red = new Redis()) {
                    a(red);
                }
            }
            public Redis Use(int i) {
                Open();
                current = i;
                db = redis.GetDatabase(i);
     
                //Log.Logs($"RedisDB Conntet State: {redis.IsConnected}");
                var t = db.Ping();
                //Log.Logs($"RedisDB Select {i}, Ping.{t.TotalMilliseconds}ms");
                return this;
            }
     
            public void Set(string key, string val, TimeSpan? ts = null) {
                db.StringSet(key, val, ts);
            }
     
            public string Get(string key) {
                return db.StringGet(key);
            }
     
            public void Remove(string key) {
                db.KeyDelete(key, CommandFlags.HighPriority);
            }
     
            public bool Exists(string key) {
                return db.KeyExists(key);
            }
     
            public void Dispose() {
                db = null;
            }
     
            #region Redis发布订阅
     
            public delegate void RedisDeletegate(string str);
            public event RedisDeletegate RedisSubMessageEvent;
     
            /// <summary>
            /// 订阅
            /// </summary>
            /// <param name="subChannel"></param>
            public void RedisSub(string subChannel) {
     
                redis.GetSubscriber().Subscribe(subChannel, (channel, message) => {
                    RedisSubMessageEvent?.Invoke(message); //触发事件
     
                });
     
            }
     
            /// <summary>
            /// 发布
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="channel"></param>
            /// <param name="msg"></param>
            /// <returns></returns>
            public long RedisPub<T>(string channel, T msg) {
     
                return redis.GetSubscriber().Publish(channel, msg.Json());
            }
     
            /// <summary>
            /// 取消订阅
            /// </summary>
            /// <param name="channel"></param>
            public void Unsubscribe(string channel) {
                redis.GetSubscriber().Unsubscribe(channel);
            }
     
            /// <summary>
            /// 取消全部订阅
            /// </summary>
            public void UnsubscribeAll() {
                redis.GetSubscriber().UnsubscribeAll();
            }
     
            #endregion
        }
    }
     
    ————————————————
    版权声明:本文为CSDN博主「Qin066」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qin066/article/details/90898737

  • 相关阅读:
    netcore3.0使用Session
    docker redis使用
    协变和逆变
    HashTable、Dictionary、ConcurrentDictionary三者区别
    设计模式-行为型-解释器模式
    设计模式-行为型-备忘录模式
    jq实现批量全选与反选
    call()和apply()的用法及区别,看这个例子就明白了
    谈谈对闭包的理解
    export,import和export default的区别
  • 原文地址:https://www.cnblogs.com/grj001/p/12223005.html
Copyright © 2020-2023  润新知