这是我处理多个连接的方式。我无法直接从 EasyNetQ 找到解决方案。我不使用 MS DI 的默认 DI 适配器。而且我只使用advanced api并手动注入我需要的服务。到目前为止,它似乎有效,但肯定需要更多测试。
在 startup.cs/ConfigureServices 中
services.AddBusStation(busStationBuilder =>
{
// inject IBusStation and get the bus thru name
appSettings.RabbitMQSettings.Connections.ForEach(c =>
{
var taskQueueBus = RabbitHutch.CreateBus(c.ConnectionString, CustomServiceRegister.ServiceRegisterAction());
c.Exchanges.ForEach(async e =>
{
await taskQueueBus.Advanced.ExchangeDeclareAsync(e.Name, e.Type, e.Durable, e.AutoDelete);
});
busStationBuilder.Add(c.Name, taskQueueBus.Advanced);
busStationBuilder.AddDefaultBus(taskQueueBus);
});
});
public interface IBusStation
{
IBus DefualtBus { get; }
IAdvancedBus Get(string busName);
void Add(string busName, IAdvancedBus advancedBus);
void Add(IBus bus);
}
public class BusStation : IBusStation
{
private Dictionary<string, IAdvancedBus> BusList { get; set; } = new Dictionary<string, IAdvancedBus>();
public IBus DefualtBus { get; private set; }
public IAdvancedBus Get(string busName)
{
if (BusList.TryGetValue(busName, out IAdvancedBus advancedBus))
{
return advancedBus;
}
return null;
}
public void Add(string busName, IAdvancedBus advancedBus)
{
BusList.Add(busName, advancedBus);
}
public void Add(IBus bus)
{
this.DefualtBus = bus;
}
}
public class BusStationBuilder
{
private readonly IBusStation _BusStation;
public BusStationBuilder(IServiceCollection services, IBusStation busStation)
{
this._BusStation = busStation;
services.AddSingleton(busStation);
}
public BusStationBuilder Add(string busName, IAdvancedBus advancedBus)
{
_BusStation.Add(busName, advancedBus);
return this;
}
public BusStationBuilder AddDefaultBus(IBus bus)
{
_BusStation.Add(bus);
return this;
}
}
public static class DependencyExtensions
{
public static IServiceCollection AddBusStation(this IServiceCollection services, Action<BusStationBuilder> builder)
{
var busStationBuilder = new BusStationBuilder(services, new BusStation());
builder(busStationBuilder);
return services;
}
}
appsettings.json
"RabbitMQSettings": {
"DefaultQueue": "task.main",
"Connections": [
{
"Name": "Task_Queue",
"ConnectionString": "host=192.168.123.123;virtualHost=/;username=admin;password=password123;prefetchCount=1;persistentMessages=true;publisherConfirms=true",
"Exchanges": [
{
"Name": "Direct_Task_Queue",
"Type": "direct",
"Passive": false,
"Durable": true,
"AutoDelete": false,
"Internal": false,
"AlternateExchange": null,
"Delayed": false
}
]
}
]
},