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 28, 2018
·
18 revisions
采用autofac进行DI的管理 目前仅支持Topic模式
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 = false;
//无消费者时消息重新发送的间隔时间
options.NoConsumerMessageRetryInterval = TimeSpan.FromSeconds(3);
//开启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 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" });
}
}