├── .gitattributes ├── .gitignore ├── DotNetCore.RabbitMQ.Extensions.sln ├── DotNetCore.RabbitMQ.Extensions ├── DotNetCore.RabbitMQ.Extensions.csproj ├── IConnectionChannelPool │ ├── ConnectionChannelPool.cs │ ├── IConnectionChannelPool.cs │ └── RabbitMQOptions.cs ├── IConsumerService │ ├── ConsumerService.cs │ └── IConsumerService.cs ├── IKey │ ├── IConnectionKey.cs │ └── IServiceKey.cs ├── IPublishService │ ├── IPublishService.cs │ └── PublishService.cs └── Properties │ └── PublishProfiles │ └── FolderProfile.pubxml ├── LICENSE ├── README.md ├── TestCommon ├── TestCommon.csproj ├── 普通测试 │ ├── TestDConnection.cs │ ├── TestDConsumer.cs │ ├── TestDPublish.cs │ └── TestEPublish.cs ├── 测试不同队列消息相互传递 │ ├── TestA │ │ ├── TestAConnection.cs │ │ ├── TestAConsumer.cs │ │ └── TestAPublish.cs │ ├── TestB │ │ ├── TestBConnection.cs │ │ ├── TestBConsumer.cs │ │ └── TestBPublish.cs │ └── TestRemarks.txt └── 测试单个实例多消费者 │ ├── TestCConnection.cs │ ├── TestCConsumer.cs │ └── TestCPublish.cs ├── TestConsoleConsumer ├── Program.cs └── TestConsoleConsumer.csproj └── TestConsolePublish ├── Program.cs └── TestConsolePublish.csproj /.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 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29519.87 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{495E1D21-9ECA-4706-9063-32CAB1587236}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DotNetCore.RabbitMQ.Extensions", "DotNetCore.RabbitMQ.Extensions\DotNetCore.RabbitMQ.Extensions.csproj", "{A71BBE09-B907-4B9E-888E-377423C7F6E6}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6646651C-195D-4D77-8D89-527809D485FB}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestConsoleConsumer", "TestConsoleConsumer\TestConsoleConsumer.csproj", "{A7E97DAA-C76B-4135-BADF-796A715FF0B1}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestConsolePublish", "TestConsolePublish\TestConsolePublish.csproj", "{47A55A02-6D81-4528-B7BC-D2F4191EC7B5}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestCommon", "TestCommon\TestCommon.csproj", "{4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {A71BBE09-B907-4B9E-888E-377423C7F6E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {A71BBE09-B907-4B9E-888E-377423C7F6E6}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {A71BBE09-B907-4B9E-888E-377423C7F6E6}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {A71BBE09-B907-4B9E-888E-377423C7F6E6}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {A7E97DAA-C76B-4135-BADF-796A715FF0B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {A7E97DAA-C76B-4135-BADF-796A715FF0B1}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {A7E97DAA-C76B-4135-BADF-796A715FF0B1}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {A7E97DAA-C76B-4135-BADF-796A715FF0B1}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {47A55A02-6D81-4528-B7BC-D2F4191EC7B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {47A55A02-6D81-4528-B7BC-D2F4191EC7B5}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {47A55A02-6D81-4528-B7BC-D2F4191EC7B5}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {47A55A02-6D81-4528-B7BC-D2F4191EC7B5}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB}.Release|Any CPU.Build.0 = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(SolutionProperties) = preSolution 42 | HideSolutionNode = FALSE 43 | EndGlobalSection 44 | GlobalSection(NestedProjects) = preSolution 45 | {A71BBE09-B907-4B9E-888E-377423C7F6E6} = {495E1D21-9ECA-4706-9063-32CAB1587236} 46 | {A7E97DAA-C76B-4135-BADF-796A715FF0B1} = {6646651C-195D-4D77-8D89-527809D485FB} 47 | {47A55A02-6D81-4528-B7BC-D2F4191EC7B5} = {6646651C-195D-4D77-8D89-527809D485FB} 48 | {4D5E2CE0-A731-4B26-8CFC-72D8BEB534DB} = {6646651C-195D-4D77-8D89-527809D485FB} 49 | EndGlobalSection 50 | GlobalSection(ExtensibilityGlobals) = postSolution 51 | SolutionGuid = {B9141A2A-99D3-474A-B8D6-1B5BF625DBF3} 52 | EndGlobalSection 53 | EndGlobal 54 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/DotNetCore.RabbitMQ.Extensions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 1.0.9 6 | heyehang 7 | 8 | 基于 .NETStandard 2.0, RabbitMQ.Client (> = 5.1.2)的轻量级拓展工具 9 | GitHub User-->heyehang 10 | 11 | 1.0.9.0 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IConnectionChannelPool/ConnectionChannelPool.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading; 8 | using DotNetCore.RabbitMQ.Extensions; 9 | using Microsoft.Extensions.Logging; 10 | using RabbitMQ.Client; 11 | 12 | namespace DotNetCore.RabbitMQ.Extensions 13 | { 14 | public abstract class ConnectionChannelPool : IConnectionKey, IConnectionChannelPool, IDisposable 15 | { 16 | private static readonly object SLock = new object(); 17 | private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(initialCount: 1, maxCount: 1); 18 | private const int DefaultPoolSize = 15; 19 | private int _count; 20 | private int _maxSize; 21 | ILogger logger; 22 | private IConnection _connection; 23 | private readonly ConcurrentQueue _pool; 24 | public abstract RabbitMQOptions opt { get; } 25 | public abstract string ConnectionKey { get; } 26 | 27 | public ConnectionChannelPool(ILogger logger) 28 | { 29 | this.logger = logger; 30 | _maxSize = DefaultPoolSize; 31 | _pool = new ConcurrentQueue(); 32 | } 33 | 34 | public IConnection GetConnection() 35 | { 36 | if (_connection != null && _connection.IsOpen) 37 | { 38 | return _connection; 39 | } 40 | _connectionLock.Wait(); 41 | try 42 | { 43 | var factory = new ConnectionFactory() { HostName = opt.HostName, Port = opt.Port, VirtualHost = opt.VHost, UserName = opt.UserName, Password = opt.PassWord }; 44 | 45 | _connection = factory.CreateConnection(ConnectionKey); 46 | _connection.ConnectionShutdown += (e, s) => { logger.LogWarning($"RabbitMQ channel model 创建失败!-->{s.ReplyText}"); }; 47 | 48 | return _connection; 49 | } 50 | finally 51 | { 52 | _connectionLock.Release(); 53 | } 54 | } 55 | 56 | IModel IConnectionChannelPool.Rent() 57 | { 58 | lock (SLock) 59 | { 60 | while (_count > _maxSize) 61 | { 62 | Thread.SpinWait(1); 63 | } 64 | return Rent(); 65 | } 66 | } 67 | 68 | public virtual IModel Rent() 69 | { 70 | if (_pool.TryDequeue(out var model)) 71 | { 72 | Interlocked.Decrement(ref _count); 73 | 74 | Debug.Assert(_count >= 0); 75 | 76 | return model; 77 | } 78 | 79 | try 80 | { 81 | model = GetConnection().CreateModel(); 82 | } 83 | catch (Exception e) 84 | { 85 | logger.LogError(e, $"RabbitMQ channel model 创建失败!-->{e.StackTrace}"); 86 | Console.WriteLine(e); 87 | throw; 88 | } 89 | 90 | return model; 91 | } 92 | 93 | public void Dispose() 94 | { 95 | _maxSize = 0; 96 | 97 | while (_pool.TryDequeue(out var context)) 98 | { 99 | context.Dispose(); 100 | } 101 | } 102 | 103 | bool IConnectionChannelPool.Return(IModel connection) 104 | { 105 | return Return(connection); 106 | } 107 | 108 | public virtual bool Return(IModel connection) 109 | { 110 | if (Interlocked.Increment(ref _count) <= _maxSize) 111 | { 112 | _pool.Enqueue(connection); 113 | 114 | return true; 115 | } 116 | 117 | Interlocked.Decrement(ref _count); 118 | 119 | Debug.Assert(_maxSize == 0 || _pool.Count <= _maxSize); 120 | 121 | return false; 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IConnectionChannelPool/IConnectionChannelPool.cs: -------------------------------------------------------------------------------- 1 | using RabbitMQ.Client; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace DotNetCore.RabbitMQ.Extensions 7 | { 8 | public interface IConnectionChannelPool : IConnectionKey 9 | { 10 | IConnection GetConnection(); 11 | 12 | IModel Rent(); 13 | 14 | bool Return(IModel context); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IConnectionChannelPool/RabbitMQOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DotNetCore.RabbitMQ.Extensions 6 | { 7 | public class RabbitMQOptions 8 | { 9 | public string UserName { get; set; } 10 | public string PassWord { get; set; } 11 | 12 | public string HostName { get; set; } 13 | public string VHost { get; set; } 14 | public int Port { get; set; } = -1; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IConsumerService/ConsumerService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using RabbitMQ.Client; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace DotNetCore.RabbitMQ.Extensions 10 | { 11 | public abstract class ConsumerService : IConnectionKey, IConsumerService 12 | { 13 | ILogger logger; 14 | IConnectionChannelPool connectionChannelPool; 15 | public ConsumerService(ILogger logger, IEnumerable connectionList) 16 | { 17 | this.logger = logger; 18 | connectionChannelPool = connectionList.FirstOrDefault(e => e.ConnectionKey == ConnectionKey); 19 | if (connectionChannelPool == null) 20 | { 21 | throw new Exception($"{ServiceKey}未找到相应的ConnectionChannelPool,请确保ConnectionKey是否匹配实现"); 22 | } 23 | } 24 | public abstract string Queue { get; } 25 | 26 | public abstract bool AutoAck { get; } 27 | 28 | public abstract string ServiceKey { get; } 29 | public abstract string ConnectionKey { get; } 30 | 31 | public virtual int ConsumerTotal { get; } = 1; 32 | public virtual void Start() 33 | { 34 | for (int i = 0; i < ConsumerTotal; i++) 35 | { 36 | var channel = connectionChannelPool.Rent(); 37 | 38 | channel.QueueDeclare(queue: Queue, durable: true, exclusive: false, autoDelete: false, arguments: null); 39 | 40 | channel.BasicQos(0, 1, false); 41 | 42 | var consumer = new EventingBasicConsumer(channel); 43 | consumer.Registered += Registered; 44 | consumer.Shutdown += Shutdown; 45 | consumer.Unregistered += Unregistered; 46 | consumer.Received += (s, e) => 47 | { 48 | try 49 | { 50 | Received(s, e); 51 | if (!AutoAck) 52 | { 53 | channel.BasicAck(e.DeliveryTag, false); 54 | } 55 | } 56 | catch (Exception ex) 57 | { 58 | logger.LogError(ex, $"{ServiceKey}服务消费失败!"); 59 | if (!AutoAck) 60 | { 61 | channel.BasicReject(e.DeliveryTag, true); 62 | } 63 | throw; 64 | } 65 | }; 66 | channel.BasicConsume(queue: Queue, autoAck: AutoAck, consumer: consumer); 67 | } 68 | } 69 | 70 | public abstract void Received(object sender, BasicDeliverEventArgs e); 71 | public virtual void Registered(object sender, ConsumerEventArgs e) 72 | { } 73 | public virtual void Shutdown(object sender, ShutdownEventArgs e) 74 | { } 75 | public virtual void Unregistered(object sender, ConsumerEventArgs e) 76 | { } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IConsumerService/IConsumerService.cs: -------------------------------------------------------------------------------- 1 | using RabbitMQ.Client; 2 | using RabbitMQ.Client.Events; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace DotNetCore.RabbitMQ.Extensions 8 | { 9 | public interface IConsumerService : IServiceKey 10 | { 11 | void Start(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IKey/IConnectionKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DotNetCore.RabbitMQ.Extensions 6 | { 7 | public interface IConnectionKey 8 | { 9 | /// 10 | /// Rabbit连接池key,连接复用 11 | /// 多继承类关系注入可能会用上,示例 service.AddSingleton();service.AddSingleton(); 12 | /// 13 | string ConnectionKey { get; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IKey/IServiceKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace DotNetCore.RabbitMQ.Extensions 6 | { 7 | public interface IServiceKey 8 | { 9 | /// 10 | /// 实现服务的Key,服务发现和日志跟踪 -->示例(Namespace.Class.Method) 11 | /// 多继承类关系注入可能会用上,示例 service.AddSingleton();service.AddSingleton(); 12 | /// 13 | string ServiceKey { get; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IPublishService/IPublishService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace DotNetCore.RabbitMQ.Extensions 7 | { 8 | public interface IPublishService : IServiceKey 9 | { 10 | Task PublishAsync(object objmsg); 11 | 12 | void Publish(object objmsg); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/IPublishService/PublishService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Newtonsoft.Json; 3 | using RabbitMQ.Client; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace DotNetCore.RabbitMQ.Extensions 11 | { 12 | public abstract class PublishService : IConnectionKey, IPublishService 13 | { 14 | ILogger logger; 15 | IConnectionChannelPool connectionChannelPool; 16 | public PublishService(ILogger logger, IEnumerable connectionList) 17 | { 18 | this.logger = logger; 19 | connectionChannelPool = connectionList.FirstOrDefault(e => e.ConnectionKey == ConnectionKey); 20 | if (connectionChannelPool == null) 21 | { 22 | throw new Exception($"{ServiceKey}未找到相应的ConnectionChannelPool,请确保ConnectionKey是否匹配实现"); 23 | } 24 | } 25 | public abstract string ExchangeType { get; } 26 | public abstract string Exchange { get; } 27 | public abstract string Queue { get; } 28 | 29 | public abstract string RoutingKey { get; } 30 | 31 | public abstract string ConnectionKey { get; } 32 | public abstract string ServiceKey { get; } 33 | 34 | public virtual void BasicAcks(object objmsg) 35 | { 36 | } 37 | public virtual void BasicNacks(object objmsg) 38 | { 39 | } 40 | 41 | public void Publish(object objmsg) 42 | { 43 | var channel = connectionChannelPool.Rent(); 44 | 45 | try 46 | { 47 | channel.ConfirmSelect(); 48 | var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objmsg)); 49 | 50 | channel.ExchangeDeclare(exchange: Exchange, type: ExchangeType, true); 51 | channel.QueueDeclare(queue: Queue, durable: true, exclusive: false, autoDelete: false, arguments: null); 52 | channel.QueueBind(queue: Queue, exchange: Exchange, routingKey: RoutingKey); 53 | 54 | var properties = channel.CreateBasicProperties(); 55 | properties.DeliveryMode = 2; 56 | 57 | channel.BasicPublish(exchange: Exchange, routingKey: RoutingKey, mandatory: true, basicProperties: properties, body: body); 58 | 59 | if (channel.WaitForConfirms()) BasicAcks(objmsg); else BasicNacks(objmsg); 60 | } 61 | catch (Exception ex) 62 | { 63 | logger.LogError($"{ServiceKey}发送消息出错:{ex.StackTrace}"); 64 | throw; 65 | } 66 | finally 67 | { 68 | var returned = connectionChannelPool.Return(channel); 69 | if (!returned) 70 | { 71 | channel.Dispose(); 72 | } 73 | } 74 | } 75 | 76 | public Task PublishAsync(object objmsg) 77 | { 78 | var channel = connectionChannelPool.Rent(); 79 | try 80 | { 81 | channel.ConfirmSelect(); 82 | var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objmsg)); 83 | 84 | channel.ExchangeDeclare(exchange: Exchange, type: ExchangeType, true); 85 | channel.QueueDeclare(queue: Queue, durable: true, exclusive: false, autoDelete: false, arguments: null); 86 | channel.QueueBind(queue: Queue, exchange: Exchange, routingKey: RoutingKey); 87 | 88 | var properties = channel.CreateBasicProperties(); 89 | properties.DeliveryMode = 2; 90 | 91 | channel.BasicPublish(exchange: Exchange, routingKey: RoutingKey, mandatory: true, basicProperties: properties, body: body); 92 | 93 | if (channel.WaitForConfirms()) BasicAcks(objmsg); else BasicNacks(objmsg); 94 | return Task.CompletedTask; 95 | } 96 | catch (Exception ex) 97 | { 98 | logger.LogError($"{ServiceKey}发送消息出错:{ex.StackTrace}"); 99 | throw; 100 | } 101 | finally 102 | { 103 | var returned = connectionChannelPool.Return(channel); 104 | if (!returned) 105 | { 106 | channel.Dispose(); 107 | } 108 | } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /DotNetCore.RabbitMQ.Extensions/Properties/PublishProfiles/FolderProfile.pubxml: -------------------------------------------------------------------------------- 1 |  2 | 5 | 6 | 7 | FileSystem 8 | Release 9 | Any CPU 10 | netstandard2.0 11 | bin\Release\netstandard2.0\publish\ 12 | 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # DotNetCore.RabbitMQ.Extensions介绍 3 | 4 | * 这是一个 基于.NETStandard 2.0的Rabbit轻量级框架,可以让开发人员无需关注底层变动,专注编写业务代码,从而达到便捷开发。 5 | 6 | # 特性 7 | 8 | * DotNetCore.RabbitMQ.Extensions,非常的小巧,下面将介绍 DotNetCore.RabbitMQ.Extensions 的项目框架。 9 | * 开发设计思路是将Rabbit的连接池,生产者,消费者三种业务类型分层分离,从而实现解耦轻量化。 10 | * 连接池,生产者,消费者的设计实现逻辑采用适配器设计,实现各自之间单一职责与开闭原则,是非常有利于业务的扩展和维护。 11 | * 连接池:内置连接池管理,无需重复创建连接和信道,并采用安全线程控制。在这里用户只需要关心配置连接池相关参数。 12 | * 生产者和消费者:底层已经全部抽象实现,无须关注底层逻辑,在这里用户只需要关心配置生产者/消费者相关参数,并且消费者支持单例多重消费者。 13 | * 开发人员只需要在Rabbit管控台新建相关的VHost,其他参数(Exchange,Queue,ExchangeType,RoutingKey)全部代码自动帮你建立完好,无须手动新建,解决繁琐操作。 14 | * 项目 gitbhub 地址: 15 | 16 | --- 17 | 18 | 19 | ## 参数说明 20 | 21 | * HostName,Rabbit所在服务器地址 22 | * port,端口号 23 | * username,登录账号名称 24 | * password,登录密码 25 | * VHost,虚拟主机 26 | * Exchange,交换机 27 | * ExchangeType,交换机类型 28 | * Queue,队列名称 29 | * RoutingKey,队列与交换机绑定的key 30 | * ServiceKey,当前服务的key,推荐:nameof(当前类名) 31 | * ConnectionKey,当前连接池服务的key,推荐:nameof(当前连接池类名) 32 | * ConsumerTotal,当前消费队列所对应的消费者数量(默认为1,支持单例多重消费者,继承ConsumerService并重写ConsumerTotal即可) 33 | # 如何开始? 34 | 35 | 36 | 37 | 下载安装 DotNetCore.RabbitMQ.Extensions 38 | 39 | ``` 40 | 安装命令:Install-Package DotNetCore.RabbitMQ.Extensions 41 | ``` 42 | 43 | 44 | ## 连接池 45 | 46 | * 继承ConnectionChannelPool类,并实现相关连接池参数和连接池的唯一标识ConnectionKey。 47 | 48 | ## 示例代码 49 | 50 | ``` C# 51 | namespace TestCommon 52 | { 53 | public class TestDConnection : ConnectionChannelPool 54 | { 55 | public TestDConnection(ILogger logger) : base(logger) 56 | { 57 | } 58 | 59 | public override RabbitMQOptions opt => new RabbitMQOptions 60 | { 61 | HostName = "localhost", 62 | Port = 5672, 63 | VHost = "testd.host", 64 | UserName = "guest", 65 | PassWord = "guest" 66 | }; 67 | 68 | public override string ConnectionKey => nameof(TestDConnection); 69 | } 70 | } 71 | ``` 72 | 73 | --- 74 | 75 | ## 生产者 76 | 77 | * 继承PublishService类,并实现相关参数,并且绑定所需要使用的连接池ConnectionKey,发送队列消息:TestDPublish.Publish(objmsg);/await TestDPublish.PublishAsync(objmsg); 78 | 79 | ## 示例代码 80 | 81 | ``` C# 82 | namespace TestCommon 83 | { 84 | public class TestDPublish : PublishService 85 | { 86 | public TestDPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 87 | { 88 | } 89 | 90 | public override string ExchangeType => "direct"; 91 | 92 | public override string Exchange => "testd.ex"; 93 | 94 | public override string Queue => "testd.query"; 95 | 96 | public override string RoutingKey => "testd.key"; 97 | 98 | public override string ConnectionKey => nameof(TestDConnection); 99 | 100 | public override string ServiceKey => nameof(TestDPublish); 101 | } 102 | } 103 | ``` 104 | 105 | --- 106 | 107 | ## 消费者 108 | 109 | * 继承ConsumerService类,并实现相关参数,并且绑定所需要使用的连接池ConnectionKey,与具体业务消费逻辑。 110 | 111 | ## 示例代码 112 | 113 | ``` C# 114 | namespace TestCommon 115 | { 116 | public class TestDConsumer : ConsumerService 117 | { 118 | ILogger logger; 119 | public TestDConsumer(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 120 | { 121 | this.logger = logger; 122 | } 123 | 124 | public override string Queue => "testd.query"; 125 | 126 | public override bool AutoAck => true; 127 | 128 | public override string ServiceKey => nameof(TestDConsumer); 129 | 130 | public override string ConnectionKey => nameof(TestDConnection); 131 | 132 | public override void Received(object sender, BasicDeliverEventArgs e) 133 | { 134 | RemoveEnvironmentModel model = new RemoveEnvironmentModel(); 135 | try 136 | { 137 | model = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(e.Body)); 138 | } 139 | catch (Exception) 140 | { 141 | logger.LogError($"{ServiceKey}服务消费解析model错误"); 142 | throw; 143 | } 144 | Console.WriteLine($"消费者{ServiceKey}:收到消息"); 145 | } 146 | } 147 | } 148 | ``` 149 | 150 | --- 151 | 152 | ## 服务注册 153 | 154 | 155 | ## 示例代码 156 | 157 | ``` C# 158 | IServiceCollection services = new ServiceCollection(); 159 | 160 | services.AddLogging(); 161 | 162 | //连接池 163 | services.AddSingleton(); 164 | 165 | //消费者 166 | services.AddSingleton(); 167 | 168 | //生产者 169 | services.AddSingleton(); 170 | 171 | //启动消费监听 172 | IServiceProvider serviceProvider = services.BuildServiceProvider(); 173 | var consumerList = serviceProvider.GetService>(); 174 | Task.Run(() => 175 | { 176 | foreach (var e in consumerList) 177 | { 178 | e.Start(); 179 | } 180 | }); 181 | 182 | 183 | ``` 184 | 185 | --- 186 | -------------------------------------------------------------------------------- /TestCommon/TestCommon.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /TestCommon/普通测试/TestDConnection.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestDConnection : ConnectionChannelPool 10 | { 11 | public TestDConnection(ILogger logger) : base(logger) 12 | { 13 | } 14 | 15 | public override RabbitMQOptions opt => new RabbitMQOptions 16 | { 17 | HostName = "localhost", 18 | Port = 5672, 19 | VHost = "testd.host", 20 | UserName = "guest", 21 | PassWord = "guest" 22 | }; 23 | 24 | public override string ConnectionKey => nameof(TestDConnection); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TestCommon/普通测试/TestDConsumer.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace TestCommon 9 | { 10 | public class TestDConsumer : ConsumerService 11 | { 12 | public TestDConsumer(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 13 | { 14 | } 15 | 16 | public override string Queue => "testd.query"; 17 | 18 | public override bool AutoAck => true; 19 | 20 | public override string ServiceKey => nameof(TestDConsumer); 21 | 22 | public override string ConnectionKey => nameof(TestDConnection); 23 | 24 | public override void Received(object sender, BasicDeliverEventArgs e) 25 | { 26 | Console.WriteLine($"消费者{ServiceKey}:收到消息:{e.Body.ToString()}"); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /TestCommon/普通测试/TestDPublish.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace TestCommon 9 | { 10 | public class TestDPublish : PublishService 11 | { 12 | public TestDPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 13 | { 14 | } 15 | 16 | public override string ExchangeType => "direct"; 17 | 18 | public override string Exchange => "testd.ex"; 19 | 20 | public override string Queue => "testd.query"; 21 | 22 | public override string RoutingKey => "testd.key"; 23 | 24 | public override string ConnectionKey => nameof(TestDConnection); 25 | 26 | public override string ServiceKey => nameof(TestDPublish); 27 | public override void BasicAcks(object objmsg) 28 | { 29 | Console.WriteLine($"{nameof(TestDPublish)}发送消息成功!objmsg:{objmsg}"); 30 | } 31 | public override void BasicNacks(object objmsg) 32 | { 33 | Console.WriteLine($"{nameof(TestDPublish)}发送消息失败!objmsg:{objmsg}"); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /TestCommon/普通测试/TestEPublish.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace TestCommon 9 | { 10 | public class TestEPublish : PublishService 11 | { 12 | public TestEPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 13 | { 14 | } 15 | 16 | public override string ExchangeType => "direct"; 17 | 18 | public override string Exchange => "testd.ex"; 19 | 20 | public override string Queue => "teste.query"; 21 | 22 | public override string RoutingKey => "teste.key"; 23 | 24 | public override string ConnectionKey => nameof(TestDConnection); 25 | 26 | public override string ServiceKey => nameof(TestEPublish); 27 | 28 | public override void BasicAcks(object objmsg) 29 | { 30 | Console.WriteLine($"{nameof(TestEPublish)}发送消息成功!objmsg:{objmsg}"); 31 | } 32 | public override void BasicNacks(object objmsg) 33 | { 34 | Console.WriteLine($"{nameof(TestEPublish)}发送消息失败!objmsg:{objmsg}"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestA/TestAConnection.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestAConnection : ConnectionChannelPool 10 | { 11 | public TestAConnection(ILogger logger) : base(logger) 12 | { 13 | } 14 | 15 | public override RabbitMQOptions opt => new RabbitMQOptions 16 | { 17 | HostName = "localhost", 18 | Port = 5672, 19 | VHost = "test.host", 20 | UserName = "guest", 21 | PassWord = "guest" 22 | }; 23 | 24 | public override string ConnectionKey => nameof(TestAConnection); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestA/TestAConsumer.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using System.Linq; 8 | 9 | namespace TestCommon 10 | { 11 | public class TestAConsumer : ConsumerService 12 | { 13 | TestBPublish testBPublish; 14 | 15 | public override string Queue => "test.query"; 16 | 17 | public override string ServiceKey => nameof(TestAConsumer); 18 | 19 | public override bool AutoAck => false; 20 | 21 | public override string ConnectionKey => nameof(TestAConnection); 22 | 23 | private int count = 1; 24 | 25 | public TestAConsumer(ILogger logger, IEnumerable connectionList, TestBPublish testBPublish) : base(logger, connectionList) 26 | { 27 | this.testBPublish = testBPublish; 28 | } 29 | 30 | public override void Received(object sender, BasicDeliverEventArgs e) 31 | { 32 | Console.WriteLine($"{ServiceKey}收到第{count++}消息:{Encoding.UTF8.GetString(e.Body)}即将转发给testB消费"); 33 | 34 | testBPublish.Publish($"{Encoding.UTF8.GetString(e.Body)}"); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestA/TestAPublish.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestAPublish : PublishService 10 | { 11 | public TestAPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 12 | { 13 | } 14 | 15 | public override string ExchangeType => "direct"; 16 | 17 | public override string Exchange => "test.ex"; 18 | 19 | public override string Queue => "test.query"; 20 | 21 | public override string RoutingKey => "test.key"; 22 | 23 | public override string ServiceKey => nameof(TestAPublish); 24 | 25 | public override string ConnectionKey => nameof(TestAConnection); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestB/TestBConnection.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestBConnection : ConnectionChannelPool 10 | { 11 | public TestBConnection(ILogger logger) : base(logger) 12 | { 13 | } 14 | 15 | public override RabbitMQOptions opt => new RabbitMQOptions 16 | { 17 | HostName = "localhost", 18 | Port = 5672, 19 | VHost = "testb.host", 20 | UserName = "guest", 21 | PassWord = "guest" 22 | }; 23 | 24 | public override string ConnectionKey => nameof(TestBConnection); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestB/TestBConsumer.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | 8 | namespace TestCommon 9 | { 10 | public class TestBConsumer : ConsumerService 11 | { 12 | public override string Queue => "test.query"; 13 | 14 | public override string ServiceKey => nameof(TestBConsumer); 15 | 16 | public override bool AutoAck => false; 17 | 18 | public override string ConnectionKey => nameof(TestBConnection); 19 | 20 | private int count = 1; 21 | 22 | public TestBConsumer(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 23 | { 24 | } 25 | 26 | public override void Received(object sender, BasicDeliverEventArgs e) 27 | { 28 | Console.WriteLine($"{ServiceKey}收到testA第{count++}消息:{Encoding.UTF8.GetString(e.Body)}"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestB/TestBPublish.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestBPublish : PublishService 10 | { 11 | public TestBPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 12 | { 13 | } 14 | 15 | public override string ExchangeType => "direct"; 16 | 17 | public override string Exchange => "test.ex"; 18 | 19 | public override string Queue => "test.query"; 20 | 21 | public override string RoutingKey => "test.key"; 22 | 23 | public override string ServiceKey => nameof(TestBPublish); 24 | 25 | public override string ConnectionKey => nameof(TestBConnection); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TestCommon/测试不同队列消息相互传递/TestRemarks.txt: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 一,测试关系背景: 8 | 1,A生产者绑定A消费者 9 | 2,B生产者绑定B消费者 10 | 11 | 12 | 二,测试消息传递场景: 13 | 1,A生产消息后,A消费者消费的同时顺带的把消费的消息转发给B生产者,然后让B消费者消费。 14 | 15 | 16 | 三,消息传递导图: 17 | 1,A生产者-->A消费者-->B生产者-->B消费者 -------------------------------------------------------------------------------- /TestCommon/测试单个实例多消费者/TestCConnection.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestCConnection : ConnectionChannelPool 10 | { 11 | public TestCConnection(ILogger logger) : base(logger) 12 | { 13 | } 14 | 15 | public override RabbitMQOptions opt => new RabbitMQOptions 16 | { 17 | HostName = "localhost", 18 | Port = 5672, 19 | VHost = "testc.host", 20 | UserName = "guest", 21 | PassWord = "guest" 22 | }; 23 | 24 | public override string ConnectionKey => nameof(TestCConnection); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /TestCommon/测试单个实例多消费者/TestCConsumer.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using RabbitMQ.Client.Events; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Text; 7 | using System.Linq; 8 | 9 | namespace TestCommon 10 | { 11 | public class TestCConsumer : ConsumerService 12 | { 13 | public override string Queue => "test.query"; 14 | 15 | public override string ServiceKey => nameof(TestCConsumer); 16 | 17 | public override bool AutoAck => false; 18 | 19 | public override string ConnectionKey => nameof(TestCConnection); 20 | 21 | public override int ConsumerTotal => 10; 22 | 23 | private int count = 1; 24 | 25 | public TestCConsumer(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 26 | { 27 | } 28 | 29 | public override void Received(object sender, BasicDeliverEventArgs e) 30 | { 31 | Console.WriteLine($"{ServiceKey}收到testC第{count++}消息:{Encoding.UTF8.GetString(e.Body)}"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /TestCommon/测试单个实例多消费者/TestCPublish.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace TestCommon 8 | { 9 | public class TestCPublish : PublishService 10 | { 11 | public TestCPublish(ILogger logger, IEnumerable connectionList) : base(logger, connectionList) 12 | { 13 | } 14 | 15 | public override string ExchangeType => "direct"; 16 | 17 | public override string Exchange => "test.ex"; 18 | 19 | public override string Queue => "test.query"; 20 | 21 | public override string RoutingKey => "test.key"; 22 | 23 | public override string ServiceKey => nameof(TestCPublish); 24 | 25 | public override string ConnectionKey => nameof(TestCConnection); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /TestConsoleConsumer/Program.cs: -------------------------------------------------------------------------------- 1 | using DotNetCore.RabbitMQ.Extensions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | using TestCommon; 8 | using System.Linq; 9 | 10 | namespace TestConsoleConsumer 11 | { 12 | class Program 13 | { 14 | static void Main(string[] args) 15 | { 16 | IServiceCollection services = new ServiceCollection(); 17 | 18 | services.AddLogging(); 19 | 20 | //连接池 21 | services.AddSingleton(); 22 | services.AddSingleton(); 23 | services.AddSingleton(); 24 | services.AddSingleton(); 25 | 26 | //消费者 27 | services.AddSingleton(); 28 | services.AddSingleton(); 29 | services.AddSingleton(); 30 | services.AddSingleton(); 31 | 32 | //生产者 33 | services.AddSingleton(); 34 | 35 | //启动消费监听 36 | IServiceProvider serviceProvider = services.BuildServiceProvider(); 37 | var consumerList = serviceProvider.GetService>(); 38 | Task.Run(() => 39 | { 40 | foreach (var e in consumerList) 41 | { 42 | e.Start(); 43 | } 44 | }); 45 | 46 | Console.WriteLine("准备接受消息"); 47 | Console.ReadKey(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /TestConsoleConsumer/TestConsoleConsumer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /TestConsolePublish/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using DotNetCore.RabbitMQ.Extensions; 4 | using TestCommon; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | namespace TestConsolePublish 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | IServiceCollection services = new ServiceCollection(); 15 | 16 | services.AddLogging(); 17 | //连接池 18 | services.AddSingleton(); 19 | services.AddSingleton(); 20 | services.AddSingleton(); 21 | services.AddSingleton(); 22 | 23 | //生产者 24 | services.AddSingleton(); 25 | services.AddSingleton(); 26 | services.AddSingleton(); 27 | services.AddSingleton(); 28 | services.AddSingleton(); 29 | 30 | IServiceProvider serviceProvider = services.BuildServiceProvider(); 31 | 32 | //var testAPublish = serviceProvider.GetService(); 33 | //var testBPublish = serviceProvider.GetService(); 34 | //var testCPublish = serviceProvider.GetService(); 35 | var testDPublish = serviceProvider.GetService(); 36 | var testEPublish = serviceProvider.GetService(); 37 | 38 | #region 普通测试 39 | 40 | //while (true) 41 | //{ 42 | // Console.WriteLine("请输入要发送的消息:"); 43 | // var msg = Console.ReadLine(); 44 | // testAPublish.Publish(msg); 45 | // Console.WriteLine($"发送的消息{msg}成功"); 46 | // Console.ReadKey(); 47 | //} 48 | #endregion 普通测试 49 | 50 | //#region 压力测试 51 | //Console.WriteLine("准备压力测试,按任意键继续"); 52 | //Console.ReadKey(); 53 | //for (int i = 1; i < 10000; i++) 54 | //{ 55 | // testPublish.Publish(i); 56 | // Console.WriteLine($"发送第{i}消息成功"); 57 | //} 58 | //Console.WriteLine("压力测试完成"); 59 | //Console.ReadKey(); 60 | //#endregion 压力测试 61 | 62 | #region 测试单个实例多消费者 63 | //while (true) 64 | //{ 65 | // Console.WriteLine("请输入要发送的消息:"); 66 | // var msg = Console.ReadLine(); 67 | // testCPublish.Publish("测试单个实例多消费者"); 68 | // Console.WriteLine($"发送的消息{msg}成功"); 69 | // Console.ReadKey(); 70 | //} 71 | 72 | #endregion 测试单个实例多消费者 73 | 74 | while (true) 75 | { 76 | Console.WriteLine("请输入要发送的消息:"); 77 | var msg = Console.ReadLine(); 78 | //testEPublish.Publish("测试单个实例多消费者"); 79 | //testDPublish.Publish("测试单个实例多消费者"); 80 | testEPublish.PublishAsync("测试单个实例多消费者").Wait(); 81 | testDPublish.PublishAsync("测试单个实例多消费者").Wait(); 82 | 83 | // Console.WriteLine($"发送的消息{msg}成功"); 84 | Console.ReadKey(); 85 | } 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /TestConsolePublish/TestConsolePublish.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | --------------------------------------------------------------------------------