├── EventBus
├── EventBus.csproj
├── Events
│ └── IntegrationEvent.cs
└── Abstractions
│ ├── IIntegrationEventHandler.cs
│ └── IEventBus.cs
├── IntegrationEventLogEF
├── valueObjects
│ └── EventStateEnum.cs
├── Services
│ └── IIntegrationEventLogService.cs
├── IntegrationEventLogEF.csproj
├── IntegrationEventLogEntry.cs
└── IntegrationEventLogContext.cs
├── EventBusRabbitMQ
├── EventBusRabbitMQ.csproj
└── EventBusRabbitMQ.cs
├── .gitattributes
├── EventBusOnRabbitMQ.sln
└── .gitignore
/EventBus/EventBus.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp1.1
5 |
6 |
7 |
--------------------------------------------------------------------------------
/IntegrationEventLogEF/valueObjects/EventStateEnum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace IntegrationEventLogEF.valueObjects
6 | {
7 | public enum EventStateEnum
8 | {
9 | NotPublished = 0,
10 | Published = 1,
11 | PublishedFailed = 2
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/IntegrationEventLogEF/Services/IIntegrationEventLogService.cs:
--------------------------------------------------------------------------------
1 | using EventBus.Events;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace IntegrationEventLogEF.Services
8 | {
9 | public interface IIntegrationEventLogService
10 | {
11 | Task SaveEventAsync(IntegrationEvent @event, DbTransaction transaction);
12 | Task MarkEventAsPublishedAsync(IntegrationEvent @event);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/EventBusRabbitMQ/EventBusRabbitMQ.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp1.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/EventBus/Events/IntegrationEvent.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace EventBus.Events
6 | {
7 | ///
8 | /// 摘要:
9 | /// 事件基类型,所有的事件源都要实现此类。
10 | /// 说明:
11 | /// 表示事件处理所需的参数,也叫事件源;根据事件源可以区分出不同的事件类型,故按用途命名为事件类型。
12 | ///
13 | public class IntegrationEvent
14 | {
15 | public IntegrationEvent()
16 | {
17 | Id = Guid.NewGuid();
18 | CreationDate = DateTime.UtcNow;
19 | }
20 |
21 | public Guid Id { get; }
22 | public DateTime CreationDate { get; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/IntegrationEventLogEF/IntegrationEventLogEF.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp1.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/EventBus/Abstractions/IIntegrationEventHandler.cs:
--------------------------------------------------------------------------------
1 | using EventBus.Events;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace EventBus.Abstractions
8 | {
9 | ///
10 | /// 摘要:
11 | /// 事件处理基准接口,所有事件处理类都可实现此接口。
12 | /// 说明:
13 | /// 泛型参数支持关联事件源。
14 | ///
15 | /// 事件基类型(即事件源)
16 | public interface IIntegrationEventHandler : IIntegrationEventHandler
17 | where TIntegrationEvent : IntegrationEvent
18 | {
19 | Task Handle(TIntegrationEvent @event);
20 | }
21 |
22 | ///
23 | /// 摘要:
24 | /// 事件处理基准接口,所有事件处理类都可实现此接口。
25 | /// 说明:
26 | /// 不支持关联事件源。
27 | ///
28 | public interface IIntegrationEventHandler { }
29 | }
30 |
--------------------------------------------------------------------------------
/IntegrationEventLogEF/IntegrationEventLogEntry.cs:
--------------------------------------------------------------------------------
1 | using EventBus.Events;
2 | using IntegrationEventLogEF.valueObjects;
3 | using Newtonsoft.Json;
4 | using System;
5 |
6 | namespace IntegrationEventLogEF
7 | {
8 | public class IntegrationEventLogEntry
9 | {
10 | private IntegrationEventLogEntry() { }
11 | public IntegrationEventLogEntry(IntegrationEvent @event)
12 | {
13 | EventId = @event.Id;
14 | CreationTime = @event.CreationDate;
15 | EventTypeName = @event.GetType().FullName;
16 | Content = JsonConvert.SerializeObject(@event);
17 | State = EventStateEnum.NotPublished;
18 | TimesSent = 0;
19 | }
20 | public Guid EventId { get; private set; }
21 | public string EventTypeName { get; private set; }
22 | public EventStateEnum State { get; set; }
23 | public int TimesSent { get; set; }
24 | public DateTime CreationTime { get; private set; }
25 | public string Content { get; private set; }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/EventBus/Abstractions/IEventBus.cs:
--------------------------------------------------------------------------------
1 | using EventBus.Events;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 |
6 | namespace EventBus.Abstractions
7 | {
8 | ///
9 | /// 摘要:
10 | /// 事件总线。
11 | /// 说明:
12 | /// 集中式事件处理中心。
13 | ///
14 | public interface IEventBus
15 | {
16 | ///
17 | /// 摘要:
18 | /// 表示一个订阅事件的方法
19 | ///
20 | /// 事件类型
21 | /// 事件处理
22 | void Subscribe(IIntegrationEventHandler handler) where T : IntegrationEvent;
23 |
24 | ///
25 | /// 摘要:
26 | /// 表示一个取消订阅事件的方法
27 | ///
28 | /// 事件类型
29 | /// 事件处理
30 | void Unsubscribe(IIntegrationEventHandler handler) where T : IntegrationEvent;
31 |
32 | ///
33 | /// 摘要:
34 | /// 表示一个发布事件的方法
35 | ///
36 | /// 事件类型
37 | void Publish(IntegrationEvent @event);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/IntegrationEventLogEF/IntegrationEventLogContext.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using Microsoft.EntityFrameworkCore.Metadata.Builders;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Text;
6 |
7 | namespace IntegrationEventLogEF
8 | {
9 | public class IntegrationEventLogContext : DbContext
10 | {
11 | public IntegrationEventLogContext(DbContextOptions options) : base(options)
12 | {
13 | }
14 |
15 | public DbSet IntegrationEventLogs { get; set; }
16 |
17 | protected override void OnModelCreating(ModelBuilder builder)
18 | {
19 | builder.Entity(ConfigureIntegrationEventLogEntry);
20 | }
21 |
22 | void ConfigureIntegrationEventLogEntry(EntityTypeBuilder builder)
23 | {
24 | builder.ToTable("IntegrationEventLog");
25 |
26 | builder.HasKey(e => e.EventId);
27 |
28 | builder.Property(e => e.EventId)
29 | .IsRequired();
30 |
31 | builder.Property(e => e.Content)
32 | .IsRequired();
33 |
34 | builder.Property(e => e.CreationTime)
35 | .IsRequired();
36 |
37 | builder.Property(e => e.State)
38 | .IsRequired();
39 |
40 | builder.Property(e => e.TimesSent)
41 | .IsRequired();
42 |
43 | builder.Property(e => e.EventTypeName)
44 | .IsRequired();
45 |
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/EventBusOnRabbitMQ.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26403.7
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventBus", "EventBus\EventBus.csproj", "{43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2C11E84E-352E-4CCD-B57A-30617A7E90A8}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{4B80A113-C45E-4F73-84B1-770D18CE1FF8}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EventBusRabbitMQ", "EventBusRabbitMQ\EventBusRabbitMQ.csproj", "{EBBD3E97-CA5D-45C9-8F13-82E0436F3A96}"
13 | EndProject
14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IntegrationEventLogEF", "IntegrationEventLogEF\IntegrationEventLogEF.csproj", "{C713B659-1F74-4D9A-8C8F-3AD46904CA28}"
15 | EndProject
16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EventBus", "EventBus", "{A1221C47-5FF2-4BB5-8C71-FEE791C7767E}"
17 | EndProject
18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "solution items", "solution items", "{C3870880-D8B4-4611-AADA-B4B636DB879C}"
19 | EndProject
20 | Global
21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
22 | Debug|Any CPU = Debug|Any CPU
23 | Release|Any CPU = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
26 | {43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62}.Release|Any CPU.Build.0 = Release|Any CPU
30 | {EBBD3E97-CA5D-45C9-8F13-82E0436F3A96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
31 | {EBBD3E97-CA5D-45C9-8F13-82E0436F3A96}.Debug|Any CPU.Build.0 = Debug|Any CPU
32 | {EBBD3E97-CA5D-45C9-8F13-82E0436F3A96}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {EBBD3E97-CA5D-45C9-8F13-82E0436F3A96}.Release|Any CPU.Build.0 = Release|Any CPU
34 | {C713B659-1F74-4D9A-8C8F-3AD46904CA28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 | {C713B659-1F74-4D9A-8C8F-3AD46904CA28}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 | {C713B659-1F74-4D9A-8C8F-3AD46904CA28}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 | {C713B659-1F74-4D9A-8C8F-3AD46904CA28}.Release|Any CPU.Build.0 = Release|Any CPU
38 | EndGlobalSection
39 | GlobalSection(SolutionProperties) = preSolution
40 | HideSolutionNode = FALSE
41 | EndGlobalSection
42 | GlobalSection(NestedProjects) = preSolution
43 | {43B84C0E-E092-4EBC-AA9E-4CEA9A27CD62} = {A1221C47-5FF2-4BB5-8C71-FEE791C7767E}
44 | {EBBD3E97-CA5D-45C9-8F13-82E0436F3A96} = {A1221C47-5FF2-4BB5-8C71-FEE791C7767E}
45 | {C713B659-1F74-4D9A-8C8F-3AD46904CA28} = {A1221C47-5FF2-4BB5-8C71-FEE791C7767E}
46 | {A1221C47-5FF2-4BB5-8C71-FEE791C7767E} = {2C11E84E-352E-4CCD-B57A-30617A7E90A8}
47 | EndGlobalSection
48 | EndGlobal
49 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/EventBusRabbitMQ/EventBusRabbitMQ.cs:
--------------------------------------------------------------------------------
1 | using EventBus.Abstractions;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using EventBus.Events;
6 | using RabbitMQ.Client;
7 | using Newtonsoft.Json;
8 | using RabbitMQ.Client.Events;
9 | using System.Threading.Tasks;
10 | using System.Linq;
11 | using System.Reflection;
12 |
13 | namespace EventBusRabbitMQ
14 | {
15 | ///
16 | /// 摘要:
17 | /// 基于RabbitMQ实现的事件总线。
18 | /// 说明:
19 | /// 基于RabbitMQ提供分布式事件集中式处理的支持。
20 | ///
21 | public class EventBusRabbitMQ : IEventBus, IDisposable
22 | {
23 | private readonly string _brokerName = "event_bus_on_rabbitMQ";//消息代理名称
24 | private readonly string _connectionString;//连接到消息服务器的地址,可以为主机名或者IP地址。
25 | private readonly Dictionary> _handlers;//存储事件处理的字典
26 | private readonly List _eventTypes;//存储事件类型的列表
27 |
28 | private IModel _model;
29 | private IConnection _connection;
30 | private string _queueName;//队列名称
31 |
32 | public EventBusRabbitMQ(string connectionString)
33 | {
34 | _connectionString = connectionString;
35 | _handlers = new Dictionary>();
36 | _eventTypes = new List();
37 | }
38 |
39 | ///
40 | /// 摘要:
41 | /// 表示一个发布事件的方法
42 | /// 说明:
43 | /// 将数据类型作为消息发布到RabbitMQ服务器
44 | ///
45 | /// 事件类型
46 | public void Publish(IntegrationEvent @event)
47 | {
48 | var eventName = @event.GetType().Name;//获取事件类型名称
49 | var factory = new ConnectionFactory() { HostName = _connectionString };
50 | using (var connection = factory.CreateConnection())//建立socket连接
51 | using (var channel = connection.CreateModel())//建立通道
52 | {
53 | channel.ExchangeDeclare(exchange: _brokerName,
54 | type: "direct");//声明direct类型的交换机
55 |
56 | string message = JsonConvert.SerializeObject(@event);//序列化事件类型(参数)
57 | var body = Encoding.UTF8.GetBytes(message);//转化事件类型(参数)为RabbitMQ传递的消息类型(即二进制块)
58 | //发布消息到交换机。
59 | channel.BasicPublish(exchange: _brokerName,//将代理名称作为交换机的名称
60 | routingKey: eventName,//将事件类型名称作为队列名称
61 | basicProperties: null,
62 | body: body);
63 | }
64 | }
65 |
66 | ///
67 | /// 摘要:
68 | /// 表示一个订阅事件的方法
69 | ///
70 | /// 事件类型
71 | /// 事件处理
72 | public void Subscribe(IIntegrationEventHandler handler) where T : IntegrationEvent
73 | {
74 | var eventName = typeof(T).Name;
75 | if (_handlers.ContainsKey(eventName))
76 | {
77 | _handlers[eventName].Add(handler);
78 | }
79 | else
80 | {
81 | var channel = GetChannel();
82 | channel.QueueBind(queue: _queueName,
83 | exchange: _brokerName,
84 | routingKey: eventName);//从交换机根据事件类型获取消息。
85 | //记录事件处理
86 | _handlers.Add(eventName, new List());
87 | _handlers[eventName].Add(handler);
88 | _eventTypes.Add(typeof(T));//记录事件类型
89 | }
90 | }
91 |
92 | ///
93 | /// 摘要:
94 | /// 表示一个取消订阅事件的方法
95 | ///
96 | /// 事件类型
97 | /// 事件处理
98 | public void Unsubscribe(IIntegrationEventHandler handler) where T : IntegrationEvent
99 | {
100 | var eventName = typeof(T).Name;
101 | if (_handlers.ContainsKey(eventName) && _handlers[eventName].Contains(handler))
102 | {//如果该事件类型存在事件处理
103 | _handlers[eventName].Remove(handler);//移除事件处理
104 |
105 | if (_handlers[eventName].Count == 0)//如果该事件类型不存在其他的事件处理
106 | {
107 | _handlers.Remove(eventName);//从事件处理字典中移除事件类型
108 | var eventType = _eventTypes.Single(e => e.Name == eventName);
109 | _eventTypes.Remove(eventType);//从时间类型列表中移除事件类型。
110 | _model.QueueUnbind(queue: _queueName,
111 | exchange: _brokerName,
112 | routingKey: eventName);//与交换机解除绑定。
113 |
114 | if (_handlers.Keys.Count == 0)
115 | {
116 | _queueName = string.Empty;
117 | _model.Dispose();
118 | _connection.Dispose();
119 | }
120 |
121 | }
122 | }
123 | }
124 |
125 | public void Dispose()
126 | {
127 | _handlers.Clear();
128 | _model?.Dispose();
129 | _connection?.Dispose();
130 | }
131 |
132 | ///
133 | /// 获取通道
134 | ///
135 | ///
136 | private IModel GetChannel()
137 | {
138 | if (_model != null)
139 | {
140 | return _model;
141 | }
142 | else
143 | {
144 | (_model, _connection) = CreateConnection();
145 | return _model;
146 | }
147 | }
148 |
149 | ///
150 | /// 建立连接
151 | ///
152 | ///
153 | private (IModel model, IConnection connection) CreateConnection()
154 | {
155 | var factory = new ConnectionFactory() { HostName = _connectionString };
156 | var con = factory.CreateConnection();
157 | var channel = con.CreateModel();
158 |
159 | channel.ExchangeDeclare(exchange: _brokerName, type: "direct");//声明交换机
160 | if (string.IsNullOrEmpty(_queueName)) _queueName = channel.QueueDeclare().QueueName;//声明临时队列,并记录名称。
161 | //建立通道消费事件
162 | var consumer = new EventingBasicConsumer(channel);
163 | consumer.Received += async (model, ea) =>
164 | {
165 | var eventName = ea.RoutingKey;
166 | var message = Encoding.UTF8.GetString(ea.Body);
167 | //异步处理事件
168 | await ProcessEvent(eventName, message);
169 | };
170 | //等待消费消息。。。。。
171 | channel.BasicConsume(queue: _queueName,
172 | noAck: true,
173 | consumer: consumer);
174 |
175 | return (channel, con);
176 | }
177 |
178 | ///
179 | /// 异步处理事件
180 | ///
181 | /// 事件类型名称
182 | /// 消息(即事件[类型|参数])
183 | ///
184 | private async Task ProcessEvent(string eventName, string message)
185 | {
186 | if (_handlers.ContainsKey(eventName))//如果该事件类型存在事件处理
187 | {
188 | Type eventType = _eventTypes.Single(t => t.Name == eventName);//获取事件类型
189 | var integrationEvent = JsonConvert.DeserializeObject(message, eventType);//将消息反序列化成事件类型对象。
190 | var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);//基于事件类型,创建具体的事件处理类型。
191 | var handlers = _handlers[eventName];//获取事件处理
192 |
193 | foreach (var handler in handlers)
194 | {
195 | //将事件源作为参数,调用具体的事件处理方法。
196 | await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
197 | }
198 | }
199 | }
200 | }
201 | }
202 |
--------------------------------------------------------------------------------