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

采用autofac进行DI的管理 目前仅支持Topic模式

使用方法

在asp.net core中

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);
}

订阅处理方法

[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" });
   }
}
Clone this wiki locally