RabbitMQ.Bus
一个.netcore下的,十分简单的rabbitmq封装,基于RabbitMQ.Client
Nuget
https://www.nuget.org/packages/RabbitMQ.Bus/
https://www.nuget.org/packages/RabbitMQ.Bus.Autofac/Git
采用autofac进行DI的管理
目前仅支持Topic模式
public IServiceProvider ConfigureServices(IServiceCollection services) { var AssemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.AddMvc(); services.AddRabbitMQBus("amqp://guest:guest@192.168.0.252:5672/"); //OR services.AddRabbitMQBus("amqp://guest:guest@192.168.0.252:5672/", options => { //添加客户端可读名称 options.ClientProvidedName = AssemblyName; //关闭网络自动恢复 options.AutomaticRecoveryEnabled = false; //关闭持久化消息 options.Persistence = false; //无消费者时消息重新发送的间隔时间 options.NoConsumerMessageRetryInterval = TimeSpan.FromSeconds(3); //开启Autofac支持 //options.AddAutofac(services); //开启Autofac支持并开启butterfly支持 options.AddAutofac(services, butterfly => { butterfly.CollectorUrl = "http://192.168.0.252:9618"; butterfly.Service = AssemblyName; }); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //true为自动订阅,默认false,则采用之前的订阅方式,注入RabbitMQBusService后使用Subscribe泛型进行订阅 app.UseRabbitMQBus(true); }
使用方法
在asp.net core中
订阅处理方法
[Queue(ExchangeName = "dev.ex", RoutingKey = "send.#")] public class Person { public string Name { set; get; } } public class PersonHandler : IRabbitMQBusHandler<Person> { public Task Handle(Person message) { Console.WriteLine($"收到消息:{message.Name}"); return Task.CompletedTask; } }
发送消息
[Route("api/v1/[controller]")] public class IndexController : Controller { private readonly IRabbitMQBus _rabbit; public IndexController(IRabbitMQBus rabbit) { _rabbit = rabbit ?? throw new ArgumentNullException(nameof(rabbit)); } [HttpPost] public async Task<IActionResult> Send() { _rabbit.Publish( new { Name = "Hello RabbitMQ" }, routingKey: "send.message",exchangeName: "dev.ex"); //OR _rabbit.Publish(new Person{ Name = "Hello RabbitMQ" }); } }