使用EventBus + Redis發佈訂閱模式提高業務執行性能

前言

最近一直奔波於面試,面了幾家公司的研發。有讓我受益頗多的面試經驗,也有讓我感受浪費時間的面試經歷~
由於疫情緣由,最近宅在家裏也沒事,就想着使用Redis配合事件總線去實現下具體的業務。  面試

  • 需求

    一個簡單的電商,有幾個重要的需求點架構

    商品下單後TODO異步

    • 存儲訂單信息
    • 鎖定商品庫存
    • 消息推送商家端

    訂單支付後TODO性能

    • 存儲訂單支付信息
    • 商品庫存減小
    • 消息推送商家端
    • 會員積分調整

技術思路

這裏用控制檯實現上面的業務功能外,自行編寫一個基於C#反射特性的事件總線,方便具體業務事件的後續擴展,好比訂單支付後後續還要加會員消息推送啥的。使用Redis的發佈訂閱模式對事件處理進行異步化,提高執行性能。
因此最終技術架構就是 事件總線+Redis發佈訂閱。ui

完成事件總線

這裏先不急着將上面的訂單、支付、會員 等進行建模。先將事件總線的架子搭好。首先須要理解事件總線在業務系統的目的是什麼。
事件總線存在目的最重要的就是解耦 。咱們須要實現的效果就是針對指定事件源對象觸發事件後,但凡註冊了該事件參數的事件處理類則開始執行相關代碼。this

下圖能夠看出咱們的事件處理類均須要引用事件參數,全部事件處理類都是基於對事件參數處理的需求上來的。編碼

9d8bb75ee6ad2747e082d625ce99549f.png

可是!並非意味建立了事件處理類就必定會去執行!可否執行除了取決於事件源的觸發外就是必須有一層註冊(也可稱映射)。
在WinForm程序裏到處可見事件的綁定,如 this.button1.OnClick+=button1OnClick;
那麼在這裏我將綁定事件放置到一個字典裏。C#的字典Dictionary是個key value的鍵值對數據集合,鍵和值均可以是任意數據類型。
咱們能夠將事件處理類EventHandle和事件參數EventData做爲鍵和值存儲到字典裏。在事件源觸發時根據EventData反向找出全部的EventHandlepwa

思路就是這樣,開始編碼了。
定義事件參數接口,後續具體業務的事件參數接口均要繼承它。code

    /// <summary>
    /// 事件參數接口
    /// </summary>
    public interface IEventData
    {
        /// <summary>
        /// 事件源對象
        /// </summary>
        object Source { get; set; }

        ///// <summary>
        ///// 事件發生的數據
        ///// </summary>
        //TDataModel Data { get; set; }

        /// <summary>
        /// 事件發生時間
        /// </summary>
        DateTime Time { get; set; }
    }

  

須要一個事件處理接口,後續具體業務的事件處理接口均須要繼承它orm

    /// <summary>
    /// 事件實現接口
    /// </summary>
    public interface IEventHandle<T> where T : IEventData
    {
        /// <summary>
        /// 處理等級
        /// 方便事件總線觸發時候能夠有序的執行相應
        /// </summary>
        /// <returns></returns>
        int ExecuteLevel { get; }

        /// <summary>
        /// 事件執行
        /// </summary>
        /// <param name="eventData">事件參數</param>
        void Execute(T eventData);
    }

  

如今已經將事件參數和事件處理都抽象出來了,接下來是要實現上面說的註冊容器的實現了。

   /// <summary>
    /// 事件倉庫
    /// </summary>
    public interface IEventStore
    {
        /// <summary>
        /// 事件註冊
        /// </summary>
        /// <param name="handle">事件實現對象</param>
        /// <param name="data">事件參數</param>
        void EventRegister(Type handle, Type data);

        /// <summary>
        /// 事件取消註冊
        /// </summary>
        /// <param name="handle">事件實現對象</param>
        void EventUnRegister(Type handle);

        /// <summary>
        /// 獲取事件處理對象
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        Type GetEventHandle(Type data);

        /// <summary>
        /// 根據事件參數獲取事件處理集合
        /// </summary>
        /// <typeparam name="TEventData">事件參數類型</typeparam>
        /// <param name="data">事件參數</param>
        /// <returns></returns>
        IEnumerable<Type> GetEventHandleList<TEventData>(TEventData data);
    }

  

實現上面的接口

    /// <summary>
    /// 基於反射實現的事件倉儲
    /// 存儲事件處理對象和事件參數
    /// </summary>
    public class ReflectEventStore : IEventStore
    {
        private static Dictionary<Type, Type> StoreLst;

        public ReflectEventStore()
        {
            StoreLst = new Dictionary<Type, Type>();
        }

        public void EventRegister(Type handle, Type data)
        {
            if (handle == null || data == null) throw new NullReferenceException();
            if (StoreLst.Keys.Contains(handle))
                throw new ArgumentException($"事件總線已註冊類型爲{nameof(handle)} !");

            if (!StoreLst.TryAdd(handle, data))
                throw new Exception($"註冊{nameof(handle)}類型到事件總線失敗!");
        }


        public void EventUnRegister(Type handle)
        {
            if (handle == null) throw new NullReferenceException();
            StoreLst.Remove(handle);
        }

        public Type GetEventHandle(Type data)
        {
            if (data == null) throw new NullReferenceException();
            Type handle = StoreLst.FirstOrDefault(p => p.Value == data).Key;
            return handle;
        }

        public IEnumerable<Type> GetEventHandleList<TEventData>(TEventData data)
        {
            if (data == null) throw new NullReferenceException();
            var items = StoreLst.Where(p => p.Value == data.GetType())
                                  .Select(k => k.Key);
            return items;
        }
    }

  

根據上面代碼能夠看出來,咱們存儲到Dictionary內的是Type類型,GetEventHandleList方法最終獲取的是一個List<Type>的集合。
咱們須要在下面建立的EventBus類裏循環List<Type>而且執行這個事件處理類的Execute方法。

實現EventBus

    /// <summary>
    /// 事件總線服務
    /// </summary>
    public class EventBus : ReflectEventStore
    {

        public void Trigger<TEventData>(TEventData data, SortType sort = SortType.Asc) where TEventData : IEventData
        {
            // 這裏如需保證順序執行則必須循環兩次 - -....
            var items = GetEventHandleList(data).ToList();
            Dictionary<object, Tuple<Type, int>> ds = new Dictionary<object, Tuple<Type, int>>();

            foreach (var item in items)
            {
                var instance = Activator.CreateInstance(item);
                MethodInfo method = item.GetMethod("get_ExecuteLevel");
                int value = (int)method.Invoke(instance, null);
                ds.Add(instance, new Tuple<Type, int>(item, value));
            }

            var lst = sort == SortType.Asc ? ds.OrderBy(p => p.Value.Item2).ToList() : ds.OrderByDescending(p => p.Value.Item2).ToList();

            foreach (var k in lst)
            {
                MethodInfo method = k.Value.Item1.GetMethod("Execute");
                method.Invoke(k.Key, new object[] { data });
            }
        }
    }

  

上面能夠看到,咱們的事件總線是支持對綁定的事件處理對象進行有序處理,須要依賴下面這個枚舉

    /// <summary>
    /// 排序類型
    /// </summary>
    public enum SortType
    {
        /// <summary>
        /// 升序
        /// </summary>
        Asc = 1,
        /// <summary>
        /// 降序
        /// </summary>
        Desc = 2
    }

  

好了,至此,咱們的簡易版的事件總線就出來了~ 接下來就是去建模、實現相應的事件參數和事件處理類了。
建立訂單模型:

   /// <summary>
    /// 訂單模型
    /// </summary>
    public class OrderModel
    {
        /// <summary>
        /// 訂單ID
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// 用戶ID
        /// </summary>
        public Guid UserId { get; set; }

        /// <summary>
        /// 訂單建立時間
        /// </summary>
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 商品名稱
        /// </summary>
        public string ProductName { get; set; }

        /// <summary>
        /// 購買數量
        /// </summary>
        public int Number { get; set; }

        /// <summary>
        /// 訂單金額
        /// </summary>
        public decimal Money { get; set; }
    }

  

建立訂單下單事件參數

    public interface IOrderCreateEventData : IEventData
    {
        /// <summary>
        /// 訂單信息
        /// </summary>
        OrderModel Order { get; set; }
    }

    /// <summary>
    /// 訂單建立事件參數
    /// </summary>
    public class OrderCreateEventData : IOrderCreateEventData
    {
        public OrderModel Order { get; set; }
        public object Source { get; set; }
        public DateTime Time { get; set; }
    }

OK~接下來就是實現咱們上面需求上的那些功能了。

  • 存儲訂單信息
  • 鎖定商品庫存
  • 消息推送商家端
    這裏我不實現存儲訂單信息的事件處理對象,我默認此業務必須同步處理,至於後面兩個則能夠採起異步處理。經過下面代碼建立相應的事件處理類。
    訂單建立事件之消息推送商家端處理類。
    /// <summary>
    /// 訂單建立事件之消息處理類
    /// </summary>
    public class OrderCreateEventNotifyHandle : IEventHandle<IOrderCreateEventData>
    {
        public int ExecuteLevel { get; private set; }

        public OrderCreateEventNotifyHandle()
        {
            Console.WriteLine($"建立OrderCreateEventNotifyHandle對象");
            this.ExecuteLevel = 2;
        }

        public void Execute(IOrderCreateEventData eventData)
        {
            Thread.Sleep(1000);
            Console.WriteLine($"執行訂單建立事件之消息推送!訂單ID:{eventData.Order.Id.ToString()},商品名稱:{eventData.Order.ProductName}");
        }
       
    }

  

訂單建立消息之鎖定庫存處理類

   /// <summary>
    /// 訂單建立事件 鎖定庫存 處理類
    /// </summary>
    public class OrderCreateEventStockLockHandle : IEventHandle<IOrderCreateEventData>
    {
        public int ExecuteLevel { get; private set; }

        public OrderCreateEventStockLockHandle()
        {
            Console.WriteLine($"建立OrderCreateEventStockLockHandle對象");
            this.ExecuteLevel = 1;
        }


        public void Execute(IOrderCreateEventData eventData)
        {
            Thread.Sleep(1000);
            Console.WriteLine($"執行訂單建立事件之庫存鎖定!訂單ID:{eventData.Order.Id.ToString()},商品名稱:{eventData.Order.ProductName}");
        }
    }

  

OK~ 到main方法下開始執行訂單建立相關代碼。

        static void Main(string[] args)
        {
          
            Guid userId = Guid.NewGuid();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            EventBus eventBus = new EventBus();
            eventBus.EventRegister(typeof(OrderCreateEventNotifyHandle), typeof(OrderCreateEventData));
            eventBus.EventRegister(typeof(OrderCreateEventStockLockHandle), typeof(OrderCreateEventData));
            var order = new Order.OrderModel()
            {
                CreateTime = DateTime.Now,
                Id = Guid.NewGuid(),
                Money = (decimal)300.00,
                Number = 1,
                ProductName = "鮮花一束",
                UserId = userId
            };
            Console.WriteLine($"模擬存儲訂單");
            Thread.Sleep(1000);
            eventBus.Trigger(new OrderCreateEventData()
            {
                Order = order
            });
            stopwatch.Stop();
            Console.WriteLine($"下單總耗時:{stopwatch.ElapsedMilliseconds}毫秒");
            Console.ReadLine();
        }

  至此,咱們採起事件總線的方式成功將需求實現了,執行後結果以下:

 

 

能夠看到咱們的下單總耗時是3038毫秒,如您所見,咱們解決了代碼的耦合性可是沒有解決代碼的執行效率。
下一章,將咱們的Redis的發佈訂閱模式再加入進來,看是否能改善咱們的代碼執行效率~~

源碼在下一篇博客上提供下載地址(畢竟如今才完成一半~)

相關文章
相關標籤/搜索