幸福框架:發布訂閱模式 之 同步訂閱、異步訂閱和離線訂閱


背景

事件驅動解除了發布者和訂閱者之間的耦合,在UI層面,我明經常采用這種編程理念。服務器端最近也開始流行起來了,我也一直小范圍的在采用。今天就跟大家分享一下我寫的一個小框架。

框架原理

一張圖片勝過前言萬語。

代碼示例

下載地址:http://yunpan.cn/Q5SUcWdiA2mmk

項目結構

關鍵代碼

TestEvent.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using Happy.Event;
 8 using Happy.Event.Offline;
 9 
10 namespace Happy.Event.Demo.Simple
11 {
12     [TestEventInterceptor1Attibute(1)]
13     [TestEventInterceptor2Attibute(2)]
14     [Persistable(3)]
15     internal sealed class TestEvent : IEvent
16     {
17     }
18 }

Program.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Threading;
 7 
 8 using Microsoft.Practices.ServiceLocation;
 9 using Microsoft.Practices.Unity;
10 
11 using Happy.Event;
12 using Happy.Event.Offline;
13 
14 namespace Happy.Event.Demo.Simple
15 {
16     class Program
17     {
18         static readonly string _QueueName = "Happy.Event.Demo.Simple";
19 
20         static void Main(string[] args)
21         {
22             InitUnity();
23 
24             var writeQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);
25             EventPublisher.Current.AddService(writeQueue);
26 
27             EventPublisher.Current.Publish(new TestEvent());
28 
29             new Thread(() =>
30             {
31                 var readQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);
32                 var offlineEventProcessor = new OfflineEventProcessor(readQueue);
33 
34                 offlineEventProcessor.Start();
35             })
36             .Start();
37 
38             Console.ReadLine();
39         }
40 
41         static void InitUnity()
42         {
43             var container = new UnityContainer();
44 
45             ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));
46 
47             container.RegisterType<ISyncEventSubscriber<TestEvent>, TestSyncEventSubscriber1>("TestSyncEventSubscriber1");
48             container.RegisterType<ISyncEventSubscriber<TestEvent>, TestSyncEventSubscriber2>("TestSyncEventSubscriber2");
49             container.RegisterType<IAsyncEventSubscriber<TestEvent>, TestAsyncEventSubscriber1>("TestAsyncEventSubscriber1");
50             container.RegisterType<IAsyncEventSubscriber<TestEvent>, TestAsyncEventSubscriber2>("TestAsyncEventSubscriber2");
51             container.RegisterType<IOfflineEventSubscriber<TestEvent>, TestOfflineEventSubscriber1>("TestOfflineEventSubscriber1");
52             container.RegisterType<IOfflineEventSubscriber<TestEvent>, TestOfflineEventSubscriber2>("TestOfflineEventSubscriber2");
53         }
54     }
55 }

執行結果

備注

基於事件的編程,我在真實項目中有過實戰的,這個框架目前還沒在項目中使用。研發先行。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM