This repository has been archived by the owner on Aug 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Home
欧俊 edited this page Jun 27, 2018
·
18 revisions
采用autofac进行DI的管理 安装
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.ClientProvidedName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
//关闭网络自动恢复
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(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 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" }, routingKey: "send.message",exchangeName: "dev.ex");
//OR
_rabbit.Publish(new Person{ Name = "Hello RabbitMQ" });
}
}