85 lines
2.9 KiB
C#
85 lines
2.9 KiB
C#
using System;
|
|
using EasyNetQ;
|
|
using EasyNetQ.Topology;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace RabbitMQHelper
|
|
{
|
|
public static class InitRabbitMQSetup
|
|
{
|
|
public static void AddInitMQ(this IServiceCollection services, Action<RabbitConfig> setupAction, ILogger logger = null)
|
|
{
|
|
//#if NET5_0
|
|
services.AddHttpContextAccessor();//<IHttpContextAccessor, HttpContextAccessor>();
|
|
//#endif
|
|
|
|
var options = new RabbitConfig();
|
|
setupAction(options);
|
|
try
|
|
{
|
|
var bus = RabbitHutch.CreateBus($"host={options.Host};virtualHost={options.VirtualHost};username={options.UserName};password={options.Password}");
|
|
bus.Advanced.Connected += delegate (object sender1, ConnectedEventArgs e1) { c_Conneted(sender1, e1, logger); };
|
|
bus.Advanced.Disconnected += delegate (object sender1, DisconnectedEventArgs e1) { c_DisConnect(sender1, e1, logger); };
|
|
services.AddSingleton<IBus>(bus);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new Exception("MQ初始化异常:" + ex.Message);
|
|
}
|
|
services.AddSingleton<IRabbitConfig>(sp => options);
|
|
services.AddScoped<ISendMQMessage, SendMQMessage>();
|
|
services.AddHostedService<MQHostedService>();
|
|
|
|
if (options.ListSubscribe != null)
|
|
{
|
|
foreach (var item in options.ListSubscribe)
|
|
{
|
|
if (options.DefaultRegisterWay.ToLower() == "singleton")
|
|
{
|
|
services.TryAddSingleton(item);
|
|
}
|
|
else if (options.DefaultRegisterWay.ToLower() == "scoped")
|
|
{
|
|
services.TryAddScoped(item);
|
|
}
|
|
else if (options.DefaultRegisterWay.ToLower() == "transient")
|
|
{
|
|
services.TryAddTransient(item);
|
|
}
|
|
|
|
else
|
|
{
|
|
services.TryAddSingleton(item);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
static void c_Conneted(object sender, EventArgs e, ILogger logger)
|
|
{
|
|
if (logger == null)
|
|
{
|
|
Console.WriteLine("RabbitMQ已链接");
|
|
}
|
|
else
|
|
{
|
|
|
|
}
|
|
}
|
|
static void c_DisConnect(object sender, EventArgs e, ILogger logger)
|
|
{
|
|
if (logger == null)
|
|
{
|
|
Console.WriteLine("RabbitMQ已断开");
|
|
}
|
|
else
|
|
{
|
|
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
} |