Skip to content
This repository has been archived by the owner on Aug 25, 2022. It is now read-only.
欧俊 edited this page Jun 26, 2018 · 18 revisions

采用autofac进行DI的管理 安装

使用方法

在asp.net core中

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    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.AutomaticRecoveryEnabled = false;
        //开启持久化消息
        options.Persistence = true;
        //开启Autofac支持
        options.AddAutofac(services)
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //true为自动订阅,默认false,则采用之前的订阅方式,注入RabbitMQBusService后使用Subscribe泛型进行订阅
   app.UseRabbitMQBus(true);
}

订阅处理方法

[Queue("rabbitmq.bus.dev.test", ExchangeName = "", RoutingKey = "")]
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 RabbitMQBusService _rabbit;
   public IndexController(RabbitMQBusService rabbit)
   {
      _rabbit = rabbit ?? throw new ArgumentNullException(nameof(rabbit));
   }
   [HttpPost]
   public async Task<IActionResult> Send()
   {
      _rabbit.Publish("交换机名","队列名", new { Name = "Hello RabbitMQ" },"路由Key");
      //OR
      _rabbit.Publish(new Person{ Name = "Hello RabbitMQ" });
   }
}
Clone this wiki locally