├── .gitignore ├── EventBus ├── EventBus.sln ├── src │ ├── EventBus │ │ ├── Abstraction │ │ │ ├── IEventBus.cs │ │ │ ├── IEventBusSubscriptionsManager.cs │ │ │ ├── IEventHandlerFactory.cs │ │ │ └── IIntegrationEventHandler.cs │ │ ├── EventBus.csproj │ │ ├── EventBusBase.cs │ │ ├── EventBusBuilder.cs │ │ ├── EventBusServiceCollectionExtensions.cs │ │ ├── EventNameAttribute.cs │ │ ├── InMemoryEventBusSubscriptionsManager.cs │ │ ├── IntegrationEvent.cs │ │ ├── IocEventHandlerFactory.cs │ │ └── Local │ │ │ ├── EventBusLocal.cs │ │ │ └── EventBusLocalCollectionExtensions.cs │ ├── EventBusRabbitMQ │ │ ├── EventBus.RabbitMQ.csproj │ │ ├── EventBusRabbitMq.cs │ │ ├── EventBusRabbitMqCollectionExtensions.cs │ │ ├── EventBusRabbitMqOptions.cs │ │ ├── RabbitMqPublishConfigure.cs │ │ └── RabbitMqSubscribeConfigure.cs │ └── RabbitMQ │ │ ├── DefaultRabbitMqMessageConsumer.cs │ │ ├── DefaultRabbitMqMessageConsumerFactory.cs │ │ ├── DefaultRabbitMqPersistentConnection.cs │ │ ├── IRabbitMqMessageConsumer.cs │ │ ├── IRabbitMqMessageConsumerFactory.cs │ │ ├── IRabbitMqPersistentConnection.cs │ │ ├── RabbitMQ.csproj │ │ ├── RabbitMqCollectionExtensions.cs │ │ ├── RabbitMqConnectionConfigure.cs │ │ ├── RabbitMqExchangeDeclareConfigure.cs │ │ ├── RabbitMqOptions.cs │ │ └── RabbitMqQueueDeclareConfigure.cs └── test │ ├── PublishEvents │ ├── PublishEvents.csproj │ └── UserEvent.cs │ ├── WebApiPublish │ ├── Controllers │ │ └── WeatherForecastController.cs │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Startup.cs │ ├── WeatherForecast.cs │ ├── WebApiPublish.csproj │ ├── appsettings.Development.json │ └── appsettings.json │ └── WebApiSubscription │ ├── Controllers │ └── WeatherForecastController.cs │ ├── IntegrationEvents │ └── Handlers │ │ └── Handler.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Startup.cs │ ├── WeatherForecast.cs │ ├── WebApiSubscription.csproj │ ├── appsettings.Development.json │ └── appsettings.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # JustCode is a .NET coding add-in 131 | .JustCode 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | -------------------------------------------------------------------------------- /EventBus/EventBus.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29318.209 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{8E792E64-5256-4444-BFBD-04056F5D2238}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBus", "src\EventBus\EventBus.csproj", "{327C58A6-01FE-4726-8373-DC2A5DB962C0}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventBus.RabbitMQ", "src\EventBusRabbitMQ\EventBus.RabbitMQ.csproj", "{6EB862D7-0CBA-4174-BF4D-529AE77BC4ED}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{AA31F0EE-0E6A-4673-BACC-95A9D16520E2}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApiPublish", "test\WebApiPublish\WebApiPublish.csproj", "{C4588375-3BE6-402B-B1DD-19BFF744CD33}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApiSubscription", "test\WebApiSubscription\WebApiSubscription.csproj", "{88A41924-694E-4163-8562-675E8B59B7C2}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PublishEvents", "test\PublishEvents\PublishEvents.csproj", "{4CA00209-C7DA-48B0-9DF9-77773835810C}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RabbitMQ", "src\RabbitMQ\RabbitMQ.csproj", "{8AA5F1B6-E674-4151-A0FE-408F028E1BEE}" 21 | EndProject 22 | Global 23 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 24 | Debug|Any CPU = Debug|Any CPU 25 | Release|Any CPU = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 28 | {327C58A6-01FE-4726-8373-DC2A5DB962C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {327C58A6-01FE-4726-8373-DC2A5DB962C0}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {327C58A6-01FE-4726-8373-DC2A5DB962C0}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {327C58A6-01FE-4726-8373-DC2A5DB962C0}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {6EB862D7-0CBA-4174-BF4D-529AE77BC4ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {6EB862D7-0CBA-4174-BF4D-529AE77BC4ED}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {6EB862D7-0CBA-4174-BF4D-529AE77BC4ED}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {6EB862D7-0CBA-4174-BF4D-529AE77BC4ED}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {C4588375-3BE6-402B-B1DD-19BFF744CD33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {C4588375-3BE6-402B-B1DD-19BFF744CD33}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {C4588375-3BE6-402B-B1DD-19BFF744CD33}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {C4588375-3BE6-402B-B1DD-19BFF744CD33}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {88A41924-694E-4163-8562-675E8B59B7C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {88A41924-694E-4163-8562-675E8B59B7C2}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {88A41924-694E-4163-8562-675E8B59B7C2}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {88A41924-694E-4163-8562-675E8B59B7C2}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {4CA00209-C7DA-48B0-9DF9-77773835810C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {4CA00209-C7DA-48B0-9DF9-77773835810C}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {4CA00209-C7DA-48B0-9DF9-77773835810C}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {4CA00209-C7DA-48B0-9DF9-77773835810C}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {8AA5F1B6-E674-4151-A0FE-408F028E1BEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {8AA5F1B6-E674-4151-A0FE-408F028E1BEE}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {8AA5F1B6-E674-4151-A0FE-408F028E1BEE}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {8AA5F1B6-E674-4151-A0FE-408F028E1BEE}.Release|Any CPU.Build.0 = Release|Any CPU 52 | EndGlobalSection 53 | GlobalSection(SolutionProperties) = preSolution 54 | HideSolutionNode = FALSE 55 | EndGlobalSection 56 | GlobalSection(NestedProjects) = preSolution 57 | {327C58A6-01FE-4726-8373-DC2A5DB962C0} = {8E792E64-5256-4444-BFBD-04056F5D2238} 58 | {6EB862D7-0CBA-4174-BF4D-529AE77BC4ED} = {8E792E64-5256-4444-BFBD-04056F5D2238} 59 | {C4588375-3BE6-402B-B1DD-19BFF744CD33} = {AA31F0EE-0E6A-4673-BACC-95A9D16520E2} 60 | {88A41924-694E-4163-8562-675E8B59B7C2} = {AA31F0EE-0E6A-4673-BACC-95A9D16520E2} 61 | {4CA00209-C7DA-48B0-9DF9-77773835810C} = {AA31F0EE-0E6A-4673-BACC-95A9D16520E2} 62 | {8AA5F1B6-E674-4151-A0FE-408F028E1BEE} = {8E792E64-5256-4444-BFBD-04056F5D2238} 63 | EndGlobalSection 64 | GlobalSection(ExtensibilityGlobals) = postSolution 65 | SolutionGuid = {B06726D3-3F63-4763-826D-CA5B21572BB0} 66 | EndGlobalSection 67 | EndGlobal 68 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Abstraction/IEventBus.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace EventBus.Abstraction 4 | { 5 | public interface IEventBus 6 | { 7 | Task PublishAsync(TEvent eventData) 8 | where TEvent : IntegrationEvent; 9 | 10 | void Subscribe() 11 | where T : IntegrationEvent 12 | where TH : IIntegrationEventHandler,new(); 13 | 14 | void UnSubscribe() 15 | where T : IntegrationEvent 16 | where TH : IIntegrationEventHandler, new(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Abstraction/IEventBusSubscriptionsManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EventBus.Abstraction 5 | { 6 | /// 7 | /// 消息订阅管理器 8 | /// 9 | public interface IEventBusSubscriptionsManager : IDisposable 10 | { 11 | event EventHandler OnEventRemoved; 12 | 13 | void AddSubscription() 14 | where T : IntegrationEvent 15 | where TH : IIntegrationEventHandler, new(); 16 | 17 | void RemoveSubscription() 18 | where T : IntegrationEvent 19 | where TH : IIntegrationEventHandler, new(); 20 | 21 | 22 | void AddSubscription(Type eventType, Type handlerType); 23 | 24 | void RemoveSubscription(Type eventType, Type handlerType); 25 | 26 | 27 | bool IncludeSubscriptionsHandlesForEventName(string eventName); 28 | 29 | bool IncludeEventTypeForEventName(string eventName); 30 | 31 | List TryGetEventHandlerTypes(string eventName); 32 | 33 | Type TryGetEventTypeForEventName(string eventName); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Abstraction/IEventHandlerFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EventBus.Abstraction 4 | { 5 | public interface IEventHandlerFactory 6 | { 7 | IIntegrationEventHandler GetHandler(Type handlerType); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Abstraction/IIntegrationEventHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace EventBus.Abstraction 4 | { 5 | public interface IIntegrationEventHandler 6 | { 7 | } 8 | 9 | public interface IIntegrationEventHandler : IIntegrationEventHandler 10 | where TIntegrationEvent : IntegrationEvent 11 | { 12 | Task HandleAsync(TIntegrationEvent @event); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/EventBus.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/EventBusBase.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using System; 3 | using System.Threading.Tasks; 4 | 5 | namespace EventBus 6 | { 7 | public abstract class EventBusBase : IEventBus 8 | { 9 | public Task PublishAsync(TEvent eventData) 10 | where TEvent : IntegrationEvent 11 | { 12 | return PublishAsync(typeof(TEvent), eventData); 13 | } 14 | 15 | protected abstract Task PublishAsync(Type eventType, IntegrationEvent eventDate); 16 | 17 | public void Subscribe() 18 | where T : IntegrationEvent 19 | where TH : IIntegrationEventHandler, new() 20 | { 21 | Subscribe(typeof(T), typeof(TH)); 22 | } 23 | 24 | protected abstract void Subscribe(Type eventType, Type handlerType); 25 | 26 | public void UnSubscribe() 27 | where T : IntegrationEvent 28 | where TH : IIntegrationEventHandler, new() 29 | { 30 | UnSubscribe(typeof(T), typeof(TH)); 31 | } 32 | 33 | protected abstract void UnSubscribe(Type eventType, Type handlerType); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/EventBusBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace EventBus 4 | { 5 | public class EventBusBuilder 6 | { 7 | public EventBusBuilder(IServiceCollection services) 8 | { 9 | this.Services = services; 10 | } 11 | 12 | public virtual IServiceCollection Services { get; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/EventBusServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using EventBus; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using System; 4 | using EventBus.Abstraction; 5 | 6 | namespace Microsoft.Extensions.DependencyInjection 7 | { 8 | public static class EventBusServiceCollectionExtensions 9 | { 10 | public static EventBusBuilder AddEventBus(this IServiceCollection services) 11 | { 12 | if (services == null) 13 | { 14 | throw new ArgumentNullException(nameof(services)); 15 | } 16 | services.TryAddSingleton(); 17 | services.TryAddSingleton(); 18 | var builder = new EventBusBuilder(services); 19 | return builder; 20 | } 21 | public static EventBusBuilder AddEventHandler(this EventBusBuilder eventBusBuilder) 22 | where THandler : class, IIntegrationEventHandler 23 | where TEvent : IntegrationEvent 24 | { 25 | eventBusBuilder.Services.AddTransient(); 26 | return eventBusBuilder; 27 | } 28 | public static EventBusBuilder AddEventHandlers(this EventBusBuilder eventBusBuilder) 29 | where THandler0 : class, IIntegrationEventHandler 30 | where THandler1 : class, IIntegrationEventHandler 31 | where TEvent : IntegrationEvent 32 | { 33 | eventBusBuilder.Services.AddTransient(); 34 | eventBusBuilder.Services.AddTransient(); 35 | return eventBusBuilder; 36 | } 37 | public static EventBusBuilder AddEventHandlers(this EventBusBuilder eventBusBuilder) 38 | where THandler0 : class, IIntegrationEventHandler 39 | where THandler1 : class, IIntegrationEventHandler 40 | where THandler2 : class, IIntegrationEventHandler 41 | where TEvent : IntegrationEvent 42 | { 43 | eventBusBuilder.Services.AddTransient(); 44 | eventBusBuilder.Services.AddTransient(); 45 | eventBusBuilder.Services.AddTransient(); 46 | return eventBusBuilder; 47 | } 48 | public static EventBusBuilder AddEventHandlers(this EventBusBuilder eventBusBuilder) 49 | where THandler0 : class, IIntegrationEventHandler 50 | where THandler1 : class, IIntegrationEventHandler 51 | where THandler2 : class, IIntegrationEventHandler 52 | where THandler3 : class, IIntegrationEventHandler 53 | where TEvent : IntegrationEvent 54 | { 55 | eventBusBuilder.Services.AddTransient(); 56 | eventBusBuilder.Services.AddTransient(); 57 | eventBusBuilder.Services.AddTransient(); 58 | eventBusBuilder.Services.AddTransient(); 59 | return eventBusBuilder; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/EventNameAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace EventBus 5 | { 6 | [AttributeUsage(AttributeTargets.Class)] 7 | public class EventNameAttribute : Attribute 8 | { 9 | public virtual string Name { get; } 10 | 11 | public EventNameAttribute(string name) 12 | { 13 | if (string.IsNullOrWhiteSpace(name)) 14 | { 15 | throw new ArgumentException($"{nameof(name)} can not be null, empty or white space!"); 16 | } 17 | Name = name; 18 | } 19 | 20 | public static string GetNameOrDefault(Type eventType) 21 | { 22 | if (eventType == null) 23 | { 24 | throw new ArgumentNullException(nameof(eventType)); 25 | } 26 | return eventType 27 | .GetCustomAttributes(true) 28 | .OfType() 29 | .FirstOrDefault() 30 | ?.Name 31 | ?? eventType.FullName; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/InMemoryEventBusSubscriptionsManager.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace EventBus 8 | { 9 | public class InMemoryEventBusSubscriptionsManager : IEventBusSubscriptionsManager 10 | { 11 | public event EventHandler OnEventRemoved; 12 | 13 | private ConcurrentDictionary> _handlers { get; } 14 | private ConcurrentDictionary _eventTypes { get; } 15 | 16 | public InMemoryEventBusSubscriptionsManager() 17 | { 18 | _handlers = new ConcurrentDictionary>(); 19 | _eventTypes = new ConcurrentDictionary(); 20 | } 21 | 22 | #region AddSubscription 23 | public void AddSubscription() 24 | where T : IntegrationEvent 25 | where TH : IIntegrationEventHandler, new() 26 | { 27 | AddSubscription(typeof(T), typeof(TH)); 28 | } 29 | public void AddSubscription(Type eventType, Type handlerType) 30 | { 31 | TryAddSubscriptionEventType(eventType); 32 | TryAddSubscriptionEventHandler(eventType, handlerType); 33 | } 34 | private void TryAddSubscriptionEventType(Type eventType) 35 | { 36 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 37 | if (_eventTypes.ContainsKey(eventName)) 38 | { 39 | //duplicate event key 40 | if (_eventTypes[eventName] != eventType) 41 | { 42 | throw new ArgumentException( 43 | $"Event name {eventName} already exists,please make sure the event key is unique"); 44 | } 45 | } 46 | else 47 | { 48 | _eventTypes[eventName] = eventType; 49 | } 50 | } 51 | private void TryAddSubscriptionEventHandler(Type eventType, Type handlerType) 52 | { 53 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 54 | if (!IncludeSubscriptionsHandlesForEventName(eventName)) 55 | { 56 | _handlers.GetOrAdd(eventName, new List()); 57 | } 58 | if (_handlers[eventName].Any(s => s == handlerType)) 59 | { 60 | throw new ArgumentException( 61 | $"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); 62 | } 63 | _handlers[eventName].Add(handlerType); 64 | } 65 | #endregion 66 | 67 | #region RemoveSubscription 68 | public void RemoveSubscription() 69 | where T : IntegrationEvent 70 | where TH : IIntegrationEventHandler, new() 71 | { 72 | RemoveSubscription(typeof(T), typeof(TH)); 73 | } 74 | public void RemoveSubscription(Type eventType, Type handlerType) 75 | { 76 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 77 | var handlerToRemove = TryFindSubscriptionToRemove(eventName, handlerType); 78 | TryRemoveHandler(eventName, handlerToRemove); 79 | } 80 | private Type TryFindSubscriptionToRemove(string eventName, Type handlerType) 81 | { 82 | return !IncludeSubscriptionsHandlesForEventName(eventName) ? null : _handlers[eventName].SingleOrDefault(s => s == handlerType); 83 | } 84 | private void TryRemoveHandler(string eventName, Type subsToRemove) 85 | { 86 | if (subsToRemove == null) return; 87 | _handlers[eventName].Remove(subsToRemove); 88 | if (_handlers[eventName].Any()) return; 89 | _handlers.TryRemove(eventName, out _); 90 | RaiseOnEventRemoved(eventName); 91 | } 92 | private void RaiseOnEventRemoved(string eventName) 93 | { 94 | var handler = OnEventRemoved; 95 | _eventTypes.TryGetValue(eventName, out var eventType); 96 | handler?.Invoke(this, eventType); 97 | if (eventType != null) 98 | { 99 | _eventTypes.TryRemove(eventName, out _); 100 | } 101 | } 102 | #endregion 103 | 104 | public bool IncludeSubscriptionsHandlesForEventName(string eventName) => _handlers.ContainsKey(eventName); 105 | 106 | public bool IncludeEventTypeForEventName(string eventName) => _eventTypes.ContainsKey(eventName); 107 | 108 | public List TryGetEventHandlerTypes(string eventName) 109 | { 110 | _handlers.TryGetValue(eventName, out var handles); 111 | return handles ?? new List(); 112 | } 113 | 114 | public Type TryGetEventTypeForEventName(string eventName) 115 | { 116 | _eventTypes.TryGetValue(eventName, out var eventType); 117 | return eventType; 118 | } 119 | 120 | public void Dispose() 121 | { 122 | _handlers?.Clear(); 123 | _eventTypes?.Clear(); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/IntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EventBus 4 | { 5 | public class IntegrationEvent 6 | { 7 | public IntegrationEvent() 8 | { 9 | Id = Guid.NewGuid(); 10 | UtcCreation = DateTime.UtcNow; 11 | CreationTime = DateTime.Now; 12 | } 13 | 14 | public IntegrationEvent(Guid id, DateTime createDate) 15 | { 16 | Id = id; 17 | CreationTime = createDate; 18 | UtcCreation = DateTime.UtcNow; 19 | } 20 | public Guid Id { get; } 21 | 22 | public DateTime UtcCreation { get; } 23 | 24 | public DateTime CreationTime { get; } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/IocEventHandlerFactory.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | 5 | namespace EventBus 6 | { 7 | public class IocEventHandlerFactory : IEventHandlerFactory 8 | { 9 | private readonly IServiceScopeFactory _serviceScopeFactory; 10 | 11 | public IocEventHandlerFactory(IServiceScopeFactory serviceScopeFactory) 12 | { 13 | _serviceScopeFactory = serviceScopeFactory; 14 | } 15 | public IIntegrationEventHandler GetHandler(Type handlerType) 16 | { 17 | var scope = _serviceScopeFactory.CreateScope(); 18 | return (IIntegrationEventHandler)scope.ServiceProvider.GetRequiredService(handlerType); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Local/EventBusLocal.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Reflection; 7 | using System.Threading.Tasks; 8 | 9 | namespace EventBus.Local 10 | { 11 | public class EventBusLocal : EventBusBase, IDisposable 12 | { 13 | private readonly IEventBusSubscriptionsManager _subsManager; 14 | private readonly IEventHandlerFactory _eventHandlerFactory; 15 | private readonly ILogger _logger; 16 | 17 | public EventBusLocal(IEventBusSubscriptionsManager subsManager, 18 | IEventHandlerFactory eventHandlerFactory, 19 | ILogger logger) 20 | { 21 | _subsManager = subsManager; 22 | _eventHandlerFactory = eventHandlerFactory; 23 | _logger = logger; 24 | } 25 | 26 | protected override async Task PublishAsync(Type eventType, IntegrationEvent eventDate) 27 | { 28 | var exceptions = new List(); 29 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 30 | if (_subsManager.IncludeEventTypeForEventName(eventName)) 31 | { 32 | var eventHandleTypes = _subsManager.TryGetEventHandlerTypes(eventName); 33 | foreach (var eventHandleType in eventHandleTypes) 34 | { 35 | try 36 | { 37 | var handlerInstance = _eventHandlerFactory.GetHandler(eventHandleType); 38 | var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); 39 | await Task.Yield(); 40 | await (Task)concreteType.GetMethod("HandleAsync").Invoke(handlerInstance, new object[] { eventDate }); 41 | } 42 | catch (TargetInvocationException ex) 43 | { 44 | exceptions.Add(ex.InnerException); 45 | } 46 | catch (Exception ex) 47 | { 48 | exceptions.Add(ex); 49 | } 50 | } 51 | } 52 | else 53 | { 54 | _logger.LogWarning("No subscription for local memory event: {eventName}", eventName); 55 | } 56 | if (exceptions.Any()) 57 | { 58 | throw new AggregateException( 59 | "More than one error has occurred while triggering the event: " + eventType, exceptions); 60 | } 61 | } 62 | 63 | protected override void Subscribe(Type eventType, Type handlerType) 64 | { 65 | _subsManager.AddSubscription(eventType, handlerType); 66 | } 67 | 68 | protected override void UnSubscribe(Type eventType, Type handlerType) 69 | { 70 | _subsManager.RemoveSubscription(eventType, handlerType); 71 | } 72 | 73 | public void Dispose() 74 | { 75 | _subsManager?.Dispose(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /EventBus/src/EventBus/Local/EventBusLocalCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.Extensions.DependencyInjection; 3 | 4 | namespace EventBus.Local 5 | { 6 | public static class EventBusLocalCollectionExtensions 7 | { 8 | public static EventBusBuilder AddLocal(this EventBusBuilder eventBusBuilder) 9 | { 10 | eventBusBuilder.Services.AddSingleton(); 11 | return eventBusBuilder; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/EventBus.RabbitMQ.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/EventBusRabbitMq.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.Extensions.Logging; 3 | using Microsoft.Extensions.Options; 4 | using Newtonsoft.Json; 5 | using Polly; 6 | using RabbitMQ; 7 | using RabbitMQ.Client; 8 | using RabbitMQ.Client.Events; 9 | using RabbitMQ.Client.Exceptions; 10 | using System; 11 | using System.Collections.Concurrent; 12 | using System.Linq; 13 | using System.Net.Sockets; 14 | using System.Text; 15 | using System.Threading.Tasks; 16 | 17 | namespace EventBus.RabbitMQ 18 | { 19 | public class EventBusRabbitMq : EventBusBase, IDisposable 20 | { 21 | const string EXCHANGE_NAME = "event_bus_rabbitmq_default_exchange"; 22 | const string QUEUE_NAME = "event_bus_rabbitmq_default_queue"; 23 | private readonly IRabbitMqPersistentConnection _persistentConnection; 24 | private readonly IRabbitMqMessageConsumerFactory _rabbitMqMessageConsumerFactory; 25 | private readonly IEventBusSubscriptionsManager _subsManager; 26 | private readonly IEventHandlerFactory _eventHandlerFactory; 27 | private readonly ILogger _logger; 28 | private readonly EventBusRabbitMqOptions _eventBusRabbitMqOptions; 29 | private readonly int _retryCount = 5; 30 | private readonly object _lock = new object(); 31 | protected ConcurrentDictionary RabbitMqMessageConsumerDic { get; private set; } 32 | 33 | 34 | public EventBusRabbitMq( 35 | IRabbitMqPersistentConnection persistentConnection, 36 | IRabbitMqMessageConsumerFactory rabbitMqMessageConsumerFactory, 37 | IEventBusSubscriptionsManager subsManager, 38 | IEventHandlerFactory eventHandlerFactory, 39 | ILogger logger, 40 | IOptions options) 41 | { 42 | _eventBusRabbitMqOptions = options.Value; 43 | _persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection)); 44 | _rabbitMqMessageConsumerFactory = rabbitMqMessageConsumerFactory; 45 | _subsManager = subsManager ?? throw new ArgumentNullException(nameof(subsManager)); 46 | _eventHandlerFactory = eventHandlerFactory ?? throw new ArgumentNullException(nameof(eventHandlerFactory)); 47 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 48 | RabbitMqMessageConsumerDic = new ConcurrentDictionary(); 49 | _subsManager.OnEventRemoved += SubsManager_OnEventRemoved; 50 | } 51 | 52 | private void SubsManager_OnEventRemoved(object sender, Type eventType) 53 | { 54 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 55 | var (exchangeName, queueName) = GetSubscribeConfigure(eventType); 56 | var key = $"{exchangeName}_{queueName}"; 57 | if (!RabbitMqMessageConsumerDic.ContainsKey(key)) return; 58 | var rabbitMqMessageConsumer = RabbitMqMessageConsumerDic[key]; 59 | rabbitMqMessageConsumer.UnbindAsync(eventName); 60 | if (rabbitMqMessageConsumer.HasRoutingKeyBindingQueue()) return; 61 | rabbitMqMessageConsumer.Dispose(); 62 | RabbitMqMessageConsumerDic.TryRemove(key, out _); 63 | } 64 | 65 | protected override Task PublishAsync(Type eventType, IntegrationEvent eventDate) 66 | { 67 | if (!_persistentConnection.IsConnected) 68 | { 69 | _persistentConnection.TryConnect(); 70 | } 71 | var policy = Policy.Handle() 72 | .Or() 73 | .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => 74 | { 75 | _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", eventDate.Id, $"{time.TotalSeconds:n1}", ex.Message); 76 | }); 77 | 78 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 79 | _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", eventDate.Id, eventName); 80 | 81 | using (var channel = _persistentConnection.CreateModel()) 82 | { 83 | _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", eventDate.Id); 84 | var message = JsonConvert.SerializeObject(eventDate); 85 | var body = Encoding.UTF8.GetBytes(message); 86 | 87 | var model = channel; 88 | var exchangeName = GetPublishConfigure(); 89 | model.ExchangeDeclare(exchange: exchangeName, type: "direct", durable: true); 90 | policy.Execute(() => 91 | { 92 | var properties = model.CreateBasicProperties(); 93 | properties.DeliveryMode = 2; // persistent 94 | 95 | _logger.LogTrace("Publishing event to RabbitMQ: {EventId}", eventDate.Id); 96 | 97 | model.BasicPublish( 98 | exchange: exchangeName, 99 | routingKey: eventName, 100 | mandatory: true, 101 | basicProperties: properties, 102 | body: body); 103 | }); 104 | } 105 | return Task.CompletedTask; 106 | } 107 | 108 | protected override void Subscribe(Type eventType, Type handlerType) 109 | { 110 | var rabbitMqMessageConsumer = TeyGetOrSetMessageConsumer(eventType); 111 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 112 | _logger.LogInformation("Subscribing from event {EventName}", eventName); 113 | if (!_subsManager.IncludeSubscriptionsHandlesForEventName(eventName)) 114 | rabbitMqMessageConsumer?.BindAsync(eventName); 115 | _subsManager.AddSubscription(eventType, handlerType); 116 | 117 | } 118 | 119 | protected override void UnSubscribe(Type eventType, Type handlerType) 120 | { 121 | var eventName = EventNameAttribute.GetNameOrDefault(eventType); 122 | _logger.LogInformation("Unsubscribing from event {EventName}", eventName); 123 | _subsManager.RemoveSubscription(eventType, handlerType); 124 | } 125 | 126 | public void Dispose() 127 | { 128 | foreach (var rabbitMqMessageConsumer in RabbitMqMessageConsumerDic) 129 | { 130 | rabbitMqMessageConsumer.Value?.Dispose(); 131 | } 132 | RabbitMqMessageConsumerDic = new ConcurrentDictionary(); 133 | } 134 | 135 | private IRabbitMqMessageConsumer TeyGetOrSetMessageConsumer(Type eventType) 136 | { 137 | var (exchangeName, queueName) = GetSubscribeConfigure(eventType); 138 | var key = $"{exchangeName}_{queueName}"; 139 | if (RabbitMqMessageConsumerDic.ContainsKey(key)) 140 | return RabbitMqMessageConsumerDic[key]; 141 | lock (_lock) 142 | { 143 | if (RabbitMqMessageConsumerDic.ContainsKey(key)) 144 | return RabbitMqMessageConsumerDic[key]; 145 | 146 | var rabbitMqMessageConsumer = _rabbitMqMessageConsumerFactory.Create( 147 | new RabbitMqExchangeDeclareConfigure(exchangeName, "direct", true), 148 | new RabbitMqQueueDeclareConfigure(queueName)); 149 | rabbitMqMessageConsumer.OnMessageReceived(Consumer_Received); 150 | 151 | RabbitMqMessageConsumerDic.TryAdd(key, rabbitMqMessageConsumer); 152 | return rabbitMqMessageConsumer; 153 | } 154 | } 155 | 156 | private string GetPublishConfigure() 157 | { 158 | return string.IsNullOrEmpty(_eventBusRabbitMqOptions.RabbitMqPublishConfigure.ExchangeName) 159 | ? EXCHANGE_NAME 160 | : _eventBusRabbitMqOptions.RabbitMqPublishConfigure.ExchangeName; 161 | } 162 | 163 | private (string ExchangeName, string QueueName) GetSubscribeConfigure(Type eventType) 164 | { 165 | var subscribeConfigure = _eventBusRabbitMqOptions.RabbitSubscribeConfigures.Find(p => p.EventType == eventType); 166 | if (subscribeConfigure == null) 167 | return (EXCHANGE_NAME, QUEUE_NAME); 168 | 169 | var exchangeName = string.IsNullOrEmpty(subscribeConfigure.ExchangeName) 170 | ? EXCHANGE_NAME 171 | : subscribeConfigure.ExchangeName; 172 | 173 | var queueName = string.IsNullOrEmpty(subscribeConfigure.QueueName) 174 | ? QUEUE_NAME 175 | : subscribeConfigure.QueueName; 176 | 177 | return (exchangeName, queueName); 178 | } 179 | 180 | private async Task Consumer_Received(IModel model, BasicDeliverEventArgs eventArgs) 181 | { 182 | var eventName = eventArgs.RoutingKey; 183 | var message = Encoding.UTF8.GetString(eventArgs.Body); 184 | try 185 | { 186 | if (message.ToLowerInvariant().Contains("throw-fake-exception")) 187 | { 188 | throw new InvalidOperationException($"Fake exception requested: \"{message}\""); 189 | } 190 | await ProcessEvent(eventName, message); 191 | } 192 | catch (Exception ex) 193 | { 194 | _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message); 195 | } 196 | } 197 | 198 | private async Task ProcessEvent(string eventName, string message) 199 | { 200 | _logger.LogTrace("Processing RabbitMQ event: {eventName}", eventName); 201 | if (_subsManager.IncludeEventTypeForEventName(eventName)) 202 | { 203 | var eventHandleTypes = _subsManager.TryGetEventHandlerTypes(eventName); 204 | foreach (var eventHandleType in eventHandleTypes) 205 | { 206 | var handlerInstance = _eventHandlerFactory.GetHandler(eventHandleType); 207 | var eventType = _subsManager.TryGetEventTypeForEventName(eventName); 208 | var integrationEvent = JsonConvert.DeserializeObject(message, eventType); 209 | var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); 210 | await Task.Yield(); 211 | await (Task)concreteType.GetMethod("HandleAsync").Invoke(handlerInstance, new[] { integrationEvent }); 212 | } 213 | } 214 | else 215 | { 216 | _logger.LogWarning("No subscription for RabbitMQ event: {eventName}", eventName); 217 | } 218 | 219 | } 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/EventBusRabbitMqCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | 5 | namespace EventBus.RabbitMQ 6 | { 7 | public static class EventBusRabbitMqCollectionExtensions 8 | { 9 | public static EventBusBuilder AddRabbitMq(this EventBusBuilder eventBusBuilder, Action configure=null) 10 | { 11 | eventBusBuilder.Services.AddSingleton(); 12 | if (configure == null) return eventBusBuilder; 13 | eventBusBuilder.Services.Configure(configure); 14 | return eventBusBuilder; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/EventBusRabbitMqOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace EventBus.RabbitMQ 5 | { 6 | public class EventBusRabbitMqOptions 7 | { 8 | public RabbitMqPublishConfigure RabbitMqPublishConfigure { get; set; } 9 | 10 | 11 | public List RabbitSubscribeConfigures { get; set; } 12 | 13 | public EventBusRabbitMqOptions() 14 | { 15 | RabbitMqPublishConfigure = new RabbitMqPublishConfigure(); 16 | RabbitSubscribeConfigures = new List(); 17 | } 18 | 19 | 20 | public EventBusRabbitMqOptions AddPublishConfigure(Action configureOptions) 21 | { 22 | if (configureOptions == null) return this; 23 | configureOptions.Invoke(RabbitMqPublishConfigure); 24 | return this; 25 | } 26 | 27 | public EventBusRabbitMqOptions AddSubscribeConfigures(Action> configureOptions) 28 | { 29 | if (configureOptions == null) return this; 30 | configureOptions.Invoke(RabbitSubscribeConfigures); 31 | return this; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/RabbitMqPublishConfigure.cs: -------------------------------------------------------------------------------- 1 | namespace EventBus.RabbitMQ 2 | { 3 | public class RabbitMqPublishConfigure 4 | { 5 | public string ExchangeName { get; set; } 6 | 7 | public RabbitMqPublishConfigure() 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /EventBus/src/EventBusRabbitMQ/RabbitMqSubscribeConfigure.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EventBus.RabbitMQ 4 | { 5 | public class RabbitMqSubscribeConfigure 6 | { 7 | public Type EventType { get; set; } 8 | public string ExchangeName { get; set; } 9 | public string QueueName { get; set; } 10 | 11 | public RabbitMqSubscribeConfigure(Type eventType, string exchangeName, string queueName) 12 | { 13 | EventType = eventType; 14 | ExchangeName = exchangeName; 15 | QueueName = queueName; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/DefaultRabbitMqMessageConsumer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using RabbitMQ.Client; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Concurrent; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace RabbitMQ 12 | { 13 | public class DefaultRabbitMqMessageConsumer : IRabbitMqMessageConsumer 14 | { 15 | private readonly ILogger _logger; 16 | private readonly IRabbitMqPersistentConnection _persistentConnection; 17 | private Timer _timer; 18 | 19 | protected ConcurrentBag> ProcessEvents { get; } 20 | protected RabbitMqExchangeDeclareConfigure ExchangeDeclare { get; private set; } 21 | protected RabbitMqQueueDeclareConfigure QueueDeclare { get; private set; } 22 | protected IModel ConsumerChannel { get; private set; } 23 | 24 | protected ConcurrentDictionary BindingQueueRoutingKeys { get; } 25 | 26 | public DefaultRabbitMqMessageConsumer( 27 | IRabbitMqPersistentConnection connection, 28 | ILogger logger) 29 | { 30 | _logger = logger; 31 | _persistentConnection = connection; 32 | ProcessEvents = new ConcurrentBag>(); 33 | BindingQueueRoutingKeys = new ConcurrentDictionary(); 34 | } 35 | 36 | public void Initialize( 37 | RabbitMqExchangeDeclareConfigure exchangeDeclare, 38 | RabbitMqQueueDeclareConfigure queueDeclare) 39 | { 40 | ExchangeDeclare = exchangeDeclare; 41 | QueueDeclare = queueDeclare; 42 | InitializeTimer(); 43 | } 44 | 45 | private void InitializeTimer() 46 | { 47 | _timer = new Timer(sender => 48 | { 49 | TimerCallback(); 50 | }, this, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10)); 51 | } 52 | 53 | public void OnMessageReceived(Func processEvent) 54 | { 55 | ProcessEvents.Add(processEvent); 56 | } 57 | 58 | public Task BindAsync(string routingKey) 59 | { 60 | if (!_persistentConnection.IsConnected) 61 | { 62 | _persistentConnection.TryConnect(); 63 | } 64 | using (var channel = _persistentConnection.CreateModel()) 65 | { 66 | channel.ExchangeDeclare( 67 | exchange: ExchangeDeclare.ExchangeName, 68 | type: ExchangeDeclare.Type, 69 | durable: ExchangeDeclare.Durable, 70 | autoDelete: ExchangeDeclare.AutoDelete, 71 | arguments: ExchangeDeclare.Arguments); 72 | channel.QueueDeclare(queue: QueueDeclare.QueueName, 73 | durable: QueueDeclare.Durable, 74 | exclusive: QueueDeclare.Exclusive, 75 | autoDelete: QueueDeclare.AutoDelete, 76 | arguments: QueueDeclare.Arguments); 77 | channel.QueueBind(queue: QueueDeclare.QueueName, 78 | exchange: ExchangeDeclare.ExchangeName, 79 | routingKey: routingKey); 80 | BindingQueueRoutingKeys.TryAdd(routingKey, QueueDeclare.QueueName); 81 | } 82 | return Task.CompletedTask; 83 | } 84 | 85 | public Task UnbindAsync(string routingKey) 86 | { 87 | if (!_persistentConnection.IsConnected) 88 | { 89 | _persistentConnection.TryConnect(); 90 | } 91 | using (var channel = _persistentConnection.CreateModel()) 92 | { 93 | channel.QueueUnbind(queue: QueueDeclare.QueueName, 94 | exchange: ExchangeDeclare.ExchangeName, 95 | routingKey: routingKey); 96 | BindingQueueRoutingKeys.TryRemove(routingKey, out _); 97 | } 98 | return Task.CompletedTask; 99 | } 100 | 101 | public void Dispose() 102 | { 103 | ConsumerChannel?.Dispose(); 104 | ConsumerChannel = null; 105 | if (_timer == null) 106 | return; 107 | _timer.Dispose(); 108 | _timer = null; 109 | } 110 | 111 | private void TimerCallback() 112 | { 113 | if (ConsumerChannel != null && !ConsumerChannel.IsClosed) return; 114 | TryCreateConsumerChannel(); 115 | StartBasicConsume(); 116 | } 117 | 118 | private void TryCreateConsumerChannel() 119 | { 120 | if (ConsumerChannel != null && !ConsumerChannel.IsClosed) return; 121 | if (!_persistentConnection.IsConnected) 122 | { 123 | _persistentConnection.TryConnect(); 124 | } 125 | ConsumerChannel = _persistentConnection.CreateModel(); 126 | } 127 | 128 | private void StartBasicConsume() 129 | { 130 | var consumer = new AsyncEventingBasicConsumer(ConsumerChannel); 131 | consumer.Received += Consumer_Received; 132 | ConsumerChannel.BasicQos(0, 50, false); 133 | ConsumerChannel.BasicConsume( 134 | queue: QueueDeclare.QueueName, 135 | autoAck: false, 136 | consumer: consumer); 137 | } 138 | 139 | private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs) 140 | { 141 | var asyncEventingBasicConsumer = sender as AsyncEventingBasicConsumer; 142 | try 143 | { 144 | foreach (var processEvent in ProcessEvents) 145 | { 146 | await processEvent(asyncEventingBasicConsumer?.Model, eventArgs); 147 | } 148 | // Even on exception we take the message off the queue. 149 | // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX). 150 | // For more information see: https://www.rabbitmq.com/dlx.html 151 | asyncEventingBasicConsumer?.Model?.BasicAck(eventArgs.DeliveryTag, multiple: false); 152 | } 153 | catch (Exception ex) 154 | { 155 | _logger.LogError(ex.Message); 156 | } 157 | } 158 | 159 | public bool HasRoutingKeyBindingQueue() 160 | { 161 | return BindingQueueRoutingKeys.Any(); 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/DefaultRabbitMqMessageConsumerFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace RabbitMQ 4 | { 5 | public class DefaultRabbitMqMessageConsumerFactory : IRabbitMqMessageConsumerFactory 6 | { 7 | private readonly IServiceScopeFactory _serviceScopeFactory; 8 | 9 | public DefaultRabbitMqMessageConsumerFactory(IServiceScopeFactory serviceScopeFactory) 10 | { 11 | _serviceScopeFactory = serviceScopeFactory; 12 | } 13 | 14 | public IRabbitMqMessageConsumer Create(RabbitMqExchangeDeclareConfigure exchangeDeclare, RabbitMqQueueDeclareConfigure queueDeclare) 15 | { 16 | var consumer = (DefaultRabbitMqMessageConsumer)ActivatorUtilities.CreateInstance(_serviceScopeFactory.CreateScope().ServiceProvider, 17 | typeof(DefaultRabbitMqMessageConsumer)); 18 | consumer.Initialize(exchangeDeclare, queueDeclare); 19 | return consumer; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/DefaultRabbitMqPersistentConnection.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.Extensions.Options; 3 | using RabbitMQ.Client; 4 | using RabbitMQ.Client.Events; 5 | using RabbitMQ.Client.Exceptions; 6 | using System; 7 | using System.IO; 8 | using System.Net.Sockets; 9 | using Polly; 10 | 11 | namespace RabbitMQ 12 | { 13 | public class DefaultRabbitMqPersistentConnection 14 | : IRabbitMqPersistentConnection 15 | { 16 | private readonly IConnectionFactory _connectionFactory; 17 | private readonly ILogger _logger; 18 | private readonly int _retryCount = 6; 19 | IConnection _connection; 20 | bool _disposed; 21 | 22 | 23 | readonly object _syncRoot = new object(); 24 | 25 | public DefaultRabbitMqPersistentConnection(IOptions option, ILogger logger) 26 | { 27 | var connection = option.Value.Connection; 28 | _connectionFactory = connection.ConnectionFactory ?? throw new ArgumentNullException(nameof(connection.ConnectionFactory)); 29 | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); 30 | } 31 | 32 | public bool IsConnected => _connection != null && _connection.IsOpen && !_disposed; 33 | 34 | public IModel CreateModel() 35 | { 36 | if (!IsConnected) 37 | { 38 | throw new InvalidOperationException("No RabbitMQ connections are available to perform this action"); 39 | } 40 | 41 | return _connection.CreateModel(); 42 | } 43 | 44 | public void Dispose() 45 | { 46 | if (_disposed) return; 47 | 48 | _disposed = true; 49 | 50 | try 51 | { 52 | _connection?.Dispose(); 53 | } 54 | catch (IOException ex) 55 | { 56 | _logger.LogCritical(ex.ToString()); 57 | } 58 | } 59 | 60 | public bool TryConnect() 61 | { 62 | _logger.LogInformation("RabbitMQ Client is trying to connect"); 63 | lock (_syncRoot) 64 | { 65 | var policy = Policy.Handle() 66 | .Or() 67 | .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) => 68 | { 69 | _logger.LogWarning(ex, "RabbitMQ Client could not connect after {TimeOut}s ({ExceptionMessage})", $"{time.TotalSeconds:n1}", ex.Message); 70 | } 71 | ); 72 | 73 | policy.Execute(() => 74 | { 75 | if (!IsConnected) 76 | _connection = _connectionFactory 77 | .CreateConnection(); 78 | }); 79 | 80 | if (IsConnected) 81 | { 82 | _connection.ConnectionShutdown += OnConnectionShutdown; 83 | _connection.CallbackException += OnCallbackException; 84 | _connection.ConnectionBlocked += OnConnectionBlocked; 85 | 86 | _logger.LogInformation("RabbitMQ Client acquired a persistent connection to '{HostName}' and is subscribed to failure events", _connection.Endpoint.HostName); 87 | 88 | return true; 89 | } 90 | _logger.LogCritical("FATAL ERROR: RabbitMQ connections could not be created and opened"); 91 | return false; 92 | } 93 | } 94 | 95 | private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e) 96 | { 97 | if (_disposed) return; 98 | 99 | _logger.LogWarning("A RabbitMQ connection is on blocked. Trying to re-connect..."); 100 | 101 | TryConnect(); 102 | } 103 | 104 | private void OnCallbackException(object sender, CallbackExceptionEventArgs e) 105 | { 106 | if (_disposed) return; 107 | 108 | _logger.LogWarning("A RabbitMQ connection throw exception. Trying to re-connect..."); 109 | 110 | TryConnect(); 111 | } 112 | 113 | private void OnConnectionShutdown(object sender, ShutdownEventArgs reason) 114 | { 115 | if (_disposed) return; 116 | 117 | _logger.LogWarning("A RabbitMQ connection is on shutdown. Trying to re-connect..."); 118 | 119 | TryConnect(); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/IRabbitMqMessageConsumer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using RabbitMQ.Client; 4 | using RabbitMQ.Client.Events; 5 | 6 | namespace RabbitMQ 7 | { 8 | public interface IRabbitMqMessageConsumer:IDisposable 9 | { 10 | Task BindAsync(string routingKey); 11 | 12 | Task UnbindAsync(string routingKey); 13 | 14 | bool HasRoutingKeyBindingQueue(); 15 | 16 | void OnMessageReceived(Func processEvent); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/IRabbitMqMessageConsumerFactory.cs: -------------------------------------------------------------------------------- 1 | namespace RabbitMQ 2 | { 3 | public interface IRabbitMqMessageConsumerFactory 4 | { 5 | /// 6 | /// Creates a new . 7 | /// Avoid to create too many consumers since they are 8 | /// not disposed until end of the application. 9 | /// 10 | /// 11 | /// 12 | /// 13 | IRabbitMqMessageConsumer Create( 14 | RabbitMqExchangeDeclareConfigure exchange, 15 | RabbitMqQueueDeclareConfigure queue); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/IRabbitMqPersistentConnection.cs: -------------------------------------------------------------------------------- 1 | using RabbitMQ.Client; 2 | using System; 3 | 4 | namespace RabbitMQ 5 | { 6 | public interface IRabbitMqPersistentConnection 7 | : IDisposable 8 | { 9 | bool IsConnected { get; } 10 | 11 | bool TryConnect(); 12 | 13 | IModel CreateModel(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMQ.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMqCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | 4 | namespace RabbitMQ 5 | { 6 | public static class RabbitMqCollectionExtensions 7 | { 8 | public static IServiceCollection AddRabbitMq(this IServiceCollection services, Action configureOptions = null) 9 | { 10 | if (services == null) 11 | { 12 | throw new ArgumentNullException(nameof(services)); 13 | } 14 | services.AddSingleton(); 15 | services.AddSingleton(); 16 | if (configureOptions != null) 17 | services.Configure(configureOptions); 18 | return services; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMqConnectionConfigure.cs: -------------------------------------------------------------------------------- 1 | using RabbitMQ.Client; 2 | 3 | namespace RabbitMQ 4 | { 5 | public class RabbitMqConnectionConfigure 6 | { 7 | public string HostName { get; set; } 8 | 9 | public int Port { get; set; } 10 | 11 | public string UserName { get; set; } 12 | 13 | public string Password { get; set; } 14 | 15 | public string VirtualHost { get; set; } 16 | 17 | 18 | public ConnectionFactory ConnectionFactory 19 | { 20 | get 21 | { 22 | var connectionFactory = new ConnectionFactory() 23 | { 24 | HostName = HostName, 25 | Port = Port, 26 | UserName = UserName, 27 | Password = Password, 28 | DispatchConsumersAsync = true 29 | }; 30 | if (!string.IsNullOrWhiteSpace(this.VirtualHost)) 31 | connectionFactory.VirtualHost = this.VirtualHost; 32 | return connectionFactory; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMqExchangeDeclareConfigure.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace RabbitMQ 4 | { 5 | public class RabbitMqExchangeDeclareConfigure 6 | { 7 | public string ExchangeName { get; } 8 | 9 | public string Type { get; } 10 | 11 | public bool Durable { get; set; } 12 | 13 | public bool AutoDelete { get; set; } 14 | 15 | public IDictionary Arguments { get; } 16 | 17 | public RabbitMqExchangeDeclareConfigure() 18 | { 19 | } 20 | 21 | public RabbitMqExchangeDeclareConfigure( 22 | string exchangeName, 23 | string type, 24 | bool durable = false, 25 | bool autoDelete = false) 26 | { 27 | ExchangeName = exchangeName; 28 | Type = type; 29 | Durable = durable; 30 | AutoDelete = autoDelete; 31 | Arguments = new Dictionary(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMqOptions.cs: -------------------------------------------------------------------------------- 1 | namespace RabbitMQ 2 | { 3 | public class RabbitMqOptions 4 | { 5 | public RabbitMqConnectionConfigure Connection { get; set; } 6 | 7 | public RabbitMqOptions() 8 | { 9 | Connection = new RabbitMqConnectionConfigure(); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /EventBus/src/RabbitMQ/RabbitMqQueueDeclareConfigure.cs: -------------------------------------------------------------------------------- 1 | using RabbitMQ.Client; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | 5 | namespace RabbitMQ 6 | { 7 | public class RabbitMqQueueDeclareConfigure 8 | { 9 | [Required] 10 | public string QueueName { get; } 11 | 12 | public bool Durable { get; set; } 13 | 14 | public bool Exclusive { get; set; } 15 | 16 | public bool AutoDelete { get; set; } 17 | 18 | public IDictionary Arguments { get; } 19 | 20 | public RabbitMqQueueDeclareConfigure() 21 | { 22 | 23 | } 24 | public RabbitMqQueueDeclareConfigure( 25 | string queueName, 26 | bool durable = true, 27 | bool exclusive = false, 28 | bool autoDelete = false) 29 | { 30 | QueueName = queueName; 31 | Durable = durable; 32 | Exclusive = exclusive; 33 | AutoDelete = autoDelete; 34 | Arguments = new Dictionary(); 35 | } 36 | 37 | public virtual QueueDeclareOk Declare(IModel channel) 38 | { 39 | return channel.QueueDeclare( 40 | queue: QueueName, 41 | durable: Durable, 42 | exclusive: Exclusive, 43 | autoDelete: AutoDelete, 44 | arguments: Arguments 45 | ); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /EventBus/test/PublishEvents/PublishEvents.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /EventBus/test/PublishEvents/UserEvent.cs: -------------------------------------------------------------------------------- 1 | using EventBus; 2 | 3 | namespace PublishEvents 4 | { 5 | [EventName("UserEvent")] 6 | public class UserEvent : IntegrationEvent 7 | { 8 | public UserEvent(int age, string name) 9 | { 10 | Age = age; 11 | Name = name; 12 | } 13 | public int Age { get; set; } 14 | 15 | public string Name { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | using PublishEvents; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | 9 | namespace WebApiPublish.Controllers 10 | { 11 | [ApiController] 12 | [Route("[controller]")] 13 | public class WeatherForecastController : ControllerBase 14 | { 15 | private static readonly string[] Summaries = new[] 16 | { 17 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 18 | }; 19 | 20 | private readonly ILogger _logger; 21 | private readonly IEventBus _eventBus; 22 | 23 | public WeatherForecastController(ILogger logger, IEventBus eventBus) 24 | { 25 | _logger = logger; 26 | _eventBus = eventBus; 27 | } 28 | 29 | [HttpGet] 30 | public IEnumerable Get() 31 | { 32 | for (var i = 0; i < 1000; i++) 33 | { 34 | _eventBus.PublishAsync(new UserEvent(i, $"My name is {i}{i}{i}{i}{i}{i}{i}{i}")); 35 | } 36 | var rng = new Random(); 37 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 38 | { 39 | Date = DateTime.Now.AddDays(index), 40 | TemperatureC = rng.Next(-20, 55), 41 | Summary = Summaries[rng.Next(Summaries.Length)] 42 | }) 43 | .ToArray(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace WebApiPublish 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:65424", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "WebApiPublish": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/Startup.cs: -------------------------------------------------------------------------------- 1 | using EventBus.RabbitMQ; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using RabbitMQ; 8 | 9 | namespace WebApiPublish 10 | { 11 | public class Startup 12 | { 13 | public Startup(IConfiguration configuration) 14 | { 15 | Configuration = configuration; 16 | } 17 | 18 | public IConfiguration Configuration { get; } 19 | 20 | public void ConfigureServices(IServiceCollection services) 21 | { 22 | services.AddControllers(); 23 | 24 | services.AddRabbitMq(option => 25 | { 26 | var connection = new RabbitMqConnectionConfigure(); 27 | Configuration.Bind(typeof(RabbitMqConnectionConfigure).Name, connection); 28 | option.Connection = connection; 29 | }); 30 | services.AddEventBus() 31 | .AddRabbitMq(configureOptions => 32 | { 33 | configureOptions.AddPublishConfigure(option => { option.ExchangeName = "Customer_Exchange"; }); 34 | }); 35 | } 36 | 37 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 38 | { 39 | if (env.IsDevelopment()) 40 | { 41 | app.UseDeveloperExceptionPage(); 42 | } 43 | 44 | app.UseRouting(); 45 | 46 | app.UseAuthorization(); 47 | 48 | app.UseEndpoints(endpoints => 49 | { 50 | endpoints.MapControllers(); 51 | }); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebApiPublish 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/WebApiPublish.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "RabbitMqConnectionConfigure": { 10 | "hostName": "127.0.0.1", 11 | "userName": "guest", 12 | "password": "guest", 13 | "port": "-1", 14 | "virtualHost": "/" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /EventBus/test/WebApiPublish/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using EventBus.Abstraction; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Microsoft.Extensions.Logging; 8 | using PublishEvents; 9 | using WebApiSubscription.IntegrationEvents.Handlers; 10 | 11 | namespace WebApiSubscription.Controllers 12 | { 13 | [ApiController] 14 | [Route("[controller]")] 15 | public class WeatherForecastController : ControllerBase 16 | { 17 | private static readonly string[] Summaries = new[] 18 | { 19 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 20 | }; 21 | 22 | private readonly ILogger _logger; 23 | private readonly IEventBus _eventBus; 24 | 25 | public WeatherForecastController(ILogger logger,IEventBus eventBus) 26 | { 27 | _logger = logger; 28 | _eventBus = eventBus; 29 | } 30 | 31 | [HttpGet] 32 | public IEnumerable Get() 33 | { 34 | var rng = new Random(); 35 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 36 | { 37 | Date = DateTime.Now.AddDays(index), 38 | TemperatureC = rng.Next(-20, 55), 39 | Summary = Summaries[rng.Next(Summaries.Length)] 40 | }) 41 | .ToArray(); 42 | } 43 | [HttpGet("unsub")] 44 | public string UnSubscribe() 45 | { 46 | _eventBus.UnSubscribe(); 47 | return "UnSubscribe"; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/IntegrationEvents/Handlers/Handler.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using PublishEvents; 3 | using System; 4 | using System.Threading.Tasks; 5 | 6 | namespace WebApiSubscription.IntegrationEvents.Handlers 7 | { 8 | public class UserEventHandler 9 | : IIntegrationEventHandler 10 | { 11 | public async Task HandleAsync(UserEvent @event) 12 | { 13 | Console.WriteLine($"UserEventHandler,信息Id={@event.Name}"); 14 | await Task.Delay(50); 15 | } 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace WebApiSubscription 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:49198", 8 | "sslPort": 0 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "WebApiSubscription": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/Startup.cs: -------------------------------------------------------------------------------- 1 | using EventBus.Abstraction; 2 | using EventBus.RabbitMQ; 3 | using Microsoft.AspNetCore.Builder; 4 | using Microsoft.AspNetCore.Hosting; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using Microsoft.Extensions.Hosting; 8 | using PublishEvents; 9 | using RabbitMQ; 10 | using WebApiSubscription.IntegrationEvents.Handlers; 11 | 12 | namespace WebApiSubscription 13 | { 14 | public class Startup 15 | { 16 | public Startup(IConfiguration configuration) 17 | { 18 | Configuration = configuration; 19 | } 20 | 21 | public IConfiguration Configuration { get; } 22 | 23 | // This method gets called by the runtime. Use this method to add services to the container. 24 | public void ConfigureServices(IServiceCollection services) 25 | { 26 | services.AddControllers(); 27 | 28 | services.AddRabbitMq(option => 29 | { 30 | var connection = new RabbitMqConnectionConfigure(); 31 | Configuration.Bind(typeof(RabbitMqConnectionConfigure).Name, connection); 32 | option.Connection = connection; 33 | }); 34 | services.AddEventBus() 35 | .AddEventHandler() 36 | .AddRabbitMq(configureOptions => 37 | { 38 | configureOptions.AddSubscribeConfigures(options => 39 | { 40 | options.Add(new RabbitMqSubscribeConfigure(typeof(UserEvent), "Customer_Exchange", "Customer_Queue")); 41 | }); 42 | }); 43 | } 44 | 45 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 46 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 47 | { 48 | if (env.IsDevelopment()) 49 | { 50 | app.UseDeveloperExceptionPage(); 51 | } 52 | ConfigureEventBus(app); 53 | app.UseRouting(); 54 | app.UseAuthorization(); 55 | app.UseEndpoints(endpoints => 56 | { 57 | endpoints.MapControllers(); 58 | }); 59 | } 60 | 61 | public void ConfigureEventBus(IApplicationBuilder app) 62 | { 63 | var eventBus = app.ApplicationServices.GetRequiredService(); 64 | eventBus.Subscribe(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace WebApiSubscription 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/WebApiSubscription.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "RabbitMqConnectionConfigure": { 10 | "hostName": "127.0.0.1", 11 | "userName": "guest", 12 | "password": "guest", 13 | "port": "-1", 14 | "virtualHost": "/" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /EventBus/test/WebApiSubscription/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "RabbitMqConnectionConfigure": { 11 | "hostName": "127.0.0.1", 12 | "userName": "guest", 13 | "password": "guest", 14 | "port": "-1", 15 | "virtualHost": "/" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EventBus 2 | ## 一:使用InMemory实现EventBus 3 | #### 1.在ConfigureServices配置如下代码块 4 | ``` 5 | services.AddEventBus() 6 | .AddEventHandler() 7 | .AddLocal(); 8 | ``` 9 | #### 2.在Configure配置如下代码块(仅订阅消息时需要添加如下代码块) 10 | ``` 11 | var eventBus = app.ApplicationServices.GetRequiredService(); 12 | eventBus.Subscribe(); 13 | ``` 14 | 15 | 16 | 17 | ## 二.使用RabbitMq实现EventBus 18 | 19 | appsettings.json文件配置rabbitmq链接信息,例如: 20 | ``` 21 | "RabbitMqConnectionConfigure": { 22 | "hostName": "127.0.0.1", 23 | "userName": "guest", 24 | "password": "guest", 25 | "port": "-1", 26 | "virtualHost": "/" 27 | } 28 | ``` 29 | 30 | ### 使用方式: 31 | #### Publish 32 | 33 | ``` 34 | services.AddRabbitMq(option => 35 | { 36 | var connection = new RabbitMqConnectionConfigure(); 37 | Configuration.Bind(typeof(RabbitMqConnectionConfigure).Name, connection); 38 | option.Connection = connection; 39 | }); 40 | services.AddEventBus() 41 | .AddRabbitMq(configureOptions => 42 | { 43 | //配置发布消息所使用的交换器(若不配置,将提供默认的交换器) 44 | configureOptions.AddPublishConfigure(option => { option.ExchangeName = "Customer_Exchange"; }); 45 | }); 46 | 47 | ``` 48 | ### subscribe 49 | #### 1.在ConfigureServices配置如下代码块 50 | ``` 51 | services.AddRabbitMq(option => 52 | { 53 | var connection = new RabbitMqConnectionConfigure(); 54 | Configuration.Bind(typeof(RabbitMqConnectionConfigure).Name, connection); 55 | option.Connection = connection; 56 | }); 57 | services.AddEventBus() 58 | .AddEventHandler() 59 | .AddRabbitMq(configureOptions => 60 | { 61 | //配置订阅消息所使用的交换器和队列(若不配置,将提供默认的交换器和队列) 62 | configureOptions.AddSubscribeConfigures(options => 63 | { 64 | options.Add(new RabbitMqSubscribeConfigure(typeof(UserEvent), "Customer_Exchange", "Customer_Queue")); 65 | }); 66 | }); 67 | ``` 68 | #### 2.在Configure配置如下代码块(仅订阅消息时需要添加如下代码块) 69 | ``` 70 | var eventBus = app.ApplicationServices.GetRequiredService(); 71 | eventBus.Subscribe(); 72 | ``` 73 | --------------------------------------------------------------------------------