zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

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

Redisc# 功能 发布 订阅 使用
2023-09-11 14:21:56 时间

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