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

业务场景

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

 

发布示例

            for (var i = 1; i < 20; i++) {

                Redis.Using(rd => { rd.Use(1).RedisPub("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 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;

        /// 
        /// 订阅
        /// 
        /// 
        public void RedisSub(string subChannel) {

            redis.GetSubscriber().Subscribe(subChannel, (channel, message) => {
                RedisSubMessageEvent?.Invoke(message); //触发事件

            });

        }

        /// 
        /// 发布
        /// 
        /// 
        /// 
        /// 
        /// 
        public long RedisPub(string channel, T msg) {

            return redis.GetSubscriber().Publish(channel, msg.Json());
        }

        /// 
        /// 取消订阅
        /// 
        /// 
        public void Unsubscribe(string channel) {
            redis.GetSubscriber().Unsubscribe(channel);
        }

        /// 
        /// 取消全部订阅
        /// 
        public void UnsubscribeAll() {
            redis.GetSubscriber().UnsubscribeAll();
        }

        #endregion
    }
}

 

你可能感兴趣的:(C#,Redis)