-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathServiceBusManager.cs
106 lines (86 loc) · 3.27 KB
/
ServiceBusManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using AA.ServiceBus.Configuration;
using MassTransit;
using MassTransit.RabbitMqTransport;
using MassTransit.Util;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace AA.ServiceBus
{
public class ServiceBusManager
{
private static readonly Lazy<ServiceBusManager> _Instance = new Lazy<ServiceBusManager>(() => new ServiceBusManager());
public static ServiceBusManager Instance => _Instance.Value;
public ServiceBusConfiguration ServiceBusConfiguration { get; set; }
private IBusControl _bus;
private ServiceBusManager()
{
ServiceBusConfiguration = new ServiceBusConfiguration();
}
public ServiceBusManager UseRabbitMq(string rabbitMqUri, string rabbitMqUserName, string rabbitMqPassword)
{
ServiceBusConfiguration.RabbitMqUri = rabbitMqUri;
ServiceBusConfiguration.RabbitMqUserName = rabbitMqUserName;
ServiceBusConfiguration.RabbitMqPassword = rabbitMqPassword;
return this;
}
public ServiceBusManager RegisterConsumer<TConsumer>(string queueName = null) where TConsumer : class, IConsumer, new()
{
Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> action = (cfg, host) =>
{
if (queueName == null)
{
cfg.ReceiveEndpoint(host, ConfigureReceiveEndpoint<TConsumer>());
}
else
{
cfg.ReceiveEndpoint(host, queueName, ConfigureReceiveEndpoint<TConsumer>());
}
};
ServiceBusConfiguration.BeforeBuildActions.Add(action);
return this;
}
public ISendEndpoint BuildCommandProducer(string queueName)
{
_bus = Build();
if (!ServiceBusConfiguration.RabbitMqUri.EndsWith("/"))
{
queueName = queueName.Insert(0, "/");
}
var sendToUri = new Uri($"{ServiceBusConfiguration.RabbitMqUri}{queueName}");
return TaskUtil.Await(() => _bus.GetSendEndpoint(sendToUri));
}
public IBusControl BuildEventProducer()
{
_bus = Build();
return _bus;
}
public IBusControl Build()
{
return Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(ServiceBusConfiguration.RabbitMqUri), hst =>
{
hst.Username(ServiceBusConfiguration.RabbitMqUserName);
hst.Password(ServiceBusConfiguration.RabbitMqPassword);
});
foreach (Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> action in ServiceBusConfiguration.BeforeBuildActions)
{
action.Invoke(cfg, host);
}
});
}
public BusHandle Start()
{
return TaskUtil.Await(() => _bus.StartAsync());
}
private Action<IRabbitMqReceiveEndpointConfigurator> ConfigureReceiveEndpoint<TConsumer>() where TConsumer : class, IConsumer, new()
{
return _ =>
{
_.Consumer<TConsumer>();
};
}
}
}