本示例通过对服务订阅的封装、隐藏细节实现、统一配置、自动重连、异常处理等各个方面来打造一个简单易用的 RabbitMQ 工厂;本文适合适合有一定 RabbitMQ 使用经验的读者阅读,如果你还没有实际使用过 RabbitMQ,也没有关系,因为本文的代码都是基于直接运行的实例,通过简单的修改 RabbitMQ 即可运行。
首先,创建一个 .netcore 控制台项目,创建 Helper、Service、Utils 文件夹,分别用于存放通道管理、服务订阅、公共组件。
public class MQConfig
{
///
/// 访问消息队列的用户名
///
public string UserName { get; set; }
///
/// 访问消息队列的密码
///
public string Password { get; set; }
///
/// 消息队列的主机地址
///
public string HostName { get; set; }
///
/// 消息队列的主机开放的端口
///
public int Port { get; set; }
}
创建 RabbitMQ 连接管理类,用于创建连接,关闭连接
创建一个消息体对象 MessageBody,用于解析和传递消息到业务系统中,在接下来的 MQChannel 类中会用到
public class MessageBody
{
public EventingBasicConsumer Consumer { get; set; }
public BasicDeliverEventArgs BasicDeliver { get; set; }
///
/// 0成功
///
public int Code { get; set; }
public string Content { get; set; }
public string ErrorMessage { get; set; }
public bool Error { get; set; }
public Exception Exception { get; set; }
}
public class MQChannel
{
public string ExchangeTypeName { get; set; }
public string ExchangeName { get; set; }
public string QueueName { get; set; }
public string RoutekeyName { get; set; }
public IConnection Connection { get; set; }
public EventingBasicConsumer Consumer { get; set; }
///
/// 外部订阅消费者通知委托
///
public Action OnReceivedCallback { get; set; }
public MQChannel(string exchangeType, string exchange, string queue, string routekey)
{
this.ExchangeTypeName = exchangeType;
this.ExchangeName = exchange;
this.QueueName = queue;
this.RoutekeyName = routekey;
}
///
/// 向当前队列发送消息
///
///
public void Publish(string content)
{
byte[] body = MQConnection.UTF8.GetBytes(content);
IBasicProperties prop = new BasicProperties();
prop.DeliveryMode = 1;
Consumer.Model.BasicPublish(this.ExchangeName, this.RoutekeyName, false, prop, body);
}
internal void Receive(object sender, BasicDeliverEventArgs e)
{
MessageBody body = new MessageBody();
try
{
string content = MQConnection.UTF8.GetString(e.Body);
body.Content = content;
body.Consumer = (EventingBasicConsumer)sender;
body.BasicDeliver = e;
}
catch (Exception ex)
{
body.ErrorMessage = $"订阅-出错{ex.Message}";
body.Exception = ex;
body.Error = true;
body.Code = 500;
}
OnReceivedCallback?.Invoke(body);
}
///
/// 设置消息处理完成标志
///
///
///
///
public void SetBasicAck(EventingBasicConsumer consumer, ulong deliveryTag, bool multiple)
{
consumer.Model.BasicAck(deliveryTag, multiple);
}
///
/// 关闭消息队列的连接
///
public void Stop()
{
if (this.Connection != null && this.Connection.IsOpen)
{
this.Connection.Close();
this.Connection.Dispose();
}
}
}
在上面的 MQChannel 类中,首先是在构造函数内对当前通道的属性进行设置,其次提供了 Publish 和 OnReceivedCallback 的委托,
当通道接收到消息的时候,会进入方法 Receive 中,在 Receive 中,经过封装成 MessageBody 对象,并调用委托 OnReceivedCallback ,将,解析好的
消息传递到外边订阅者的业务中。最终在 MQChannel 中还提供了消息确认的操作方法 SetBasicAck,供业务系统手动调用。
接着再创建一个 RabbitMQ 通道管理类,用于创建通道,代码非常简单,只有一个公共方法 CreateReceiveChannel,传入相关参数,创建一个 MQChannel 对象
public class MQChannelManager
{
public MQConnection MQConn { get; set; }
public MQChannelManager(MQConnection conn)
{
this.MQConn = conn;
}
///
/// 创建消息通道
///
///
public MQChannel CreateReceiveChannel(string exchangeType, string exchange, string queue, string routekey)
{
IModel model = this.CreateModel(exchangeType, exchange, queue, routekey);
model.BasicQos(0, 1, false);
EventingBasicConsumer consumer = this.CreateConsumer(model, queue);
MQChannel channel = new MQChannel(exchangeType, exchange, queue, routekey)
{
Connection = this.MQConn.Connection,
Consumer = consumer
};
consumer.Received += channel.Receive;
return channel;
}
///
/// 创建一个通道,包含交换机/队列/路由,并建立绑定关系
///
/// 交换机类型
/// 交换机名称
/// 队列名称
/// 路由名称
///
private IModel CreateModel(string type, string exchange, string queue, string routeKey, IDictionary arguments = null)
{
type = string.IsNullOrEmpty(type) ? "default" : type;
IModel model = this.MQConn.Connection.CreateModel();
model.BasicQos(0, 1, false);
model.QueueDeclare(queue, true, false, false, arguments);
model.QueueBind(queue, exchange, routeKey);
return model;
}
///
/// 接收消息到队列中
///
/// 消息通道
/// 队列名称
/// 订阅消息的回调事件
///
private EventingBasicConsumer CreateConsumer(IModel model, string queue)
{
EventingBasicConsumer consumer = new EventingBasicConsumer(model);
model.BasicConsume(queue, false, consumer);
return consumer;
}
}
public MQChannelManager(MQConnection conn)
{
this.MQConn = conn;
}
public class MQConnection
{
private string vhost = string.Empty;
private IConnection connection = null;
private MQConfig config = null;
///
/// 构造无 utf8 标记的编码转换器
///
public static UTF8Encoding UTF8 { get; set; } = new UTF8Encoding(false);
public MQConnection(MQConfig config, string vhost)
{
this.config = config;
this.vhost = vhost;
}
public IConnection Connection
{
get
{
if (connection == null)
{
ConnectionFactory factory = new ConnectionFactory
{
AutomaticRecoveryEnabled = true,
UserName = this.config.UserName,
Password = this.config.Password,
HostName = this.config.HostName,
VirtualHost = this.vhost,
Port = this.config.Port
};
connection = factory.CreateConnection();
}
return connection;
}
}
}
设想一下,有这样的一个业务场景,通道管理和服务管理都是相同的操作,如果这些基础操作都在一个
地方定义,且有一个默认的实现,那么后来者就不需要去关注这些技术细节,直接继承基础类后,传入相应的消息配置即可完成
消息订阅和发布操作。
public interface IService
{
///
/// 创建通道
///
/// 队列名称
/// 路由名称
/// 交换机类型
///
MQChannel CreateChannel(string queue, string routeKey, string exchangeType);
///
/// 开启订阅
///
void Start();
///
/// 停止订阅
///
void Stop();
///
/// 通道列表
///
List Channels { get; set; }
///
/// 消息队列中定义的虚拟机
///
string vHost { get; }
///
/// 消息队列中定义的交换机
///
string Exchange { get; }
}
public abstract class MQServiceBase : IService
{
internal bool started = false;
internal MQServiceBase(MQConfig config)
{
this.Config = config;
}
public MQChannel CreateChannel(string queue, string routeKey, string exchangeType)
{
MQConnection conn = new MQConnection(this.Config, this.vHost);
MQChannelManager cm = new MQChannelManager(conn);
MQChannel channel = cm.CreateReceiveChannel(exchangeType, this.Exchange, queue, routeKey);
return channel;
}
///
/// 启动订阅
///
public void Start()
{
if (started)
{
return;
}
MQConnection conn = new MQConnection(this.Config, this.vHost);
MQChannelManager manager = new MQChannelManager(conn);
foreach (var item in this.Queues)
{
MQChannel channel = manager.CreateReceiveChannel(item.ExchangeType, this.Exchange, item.Queue, item.RouterKey);
channel.OnReceivedCallback = item.OnReceived;
this.Channels.Add(channel);
}
started = true;
}
///
/// 停止订阅
///
public void Stop()
{
foreach (var c in this.Channels)
{
c.Stop();
}
this.Channels.Clear();
started = false;
}
///
/// 接收消息
///
///
public abstract void OnReceived(MessageBody message);
public List Channels { get; set; } = new List();
///
/// 消息队列配置
///
public MQConfig Config { get; set; }
///
/// 消息队列中定义的虚拟机
///
public abstract string vHost { get; }
///
/// 消息队列中定义的交换机
///
public abstract string Exchange { get; }
///
/// 定义的队列列表
///
public List Queues { get; } = new List();
}
上面的抽象类,原封不动的实现接口契约,代码非常简单,在 Start 方法中,创建通道和启动消息订阅;同时,将
通道加入属性 Channels 中,方便后面的自检服务使用;在 Start 方法中
///
/// 启动订阅
///
public void Start()
{
if (started)
{
return;
}
MQConnection conn = new MQConnection(this.Config, this.vHost);
MQChannelManager manager = new MQChannelManager(conn);
foreach (var item in this.Queues)
{
MQChannel channel = manager.CreateReceiveChannel(item.ExchangeType, this.Exchange, item.Queue, item.RouterKey);
channel.OnReceivedCallback = item.OnReceived;
this.Channels.Add(channel);
}
started = true;
}
使用 MQChannelManager 创建了一个通道,并将通道的回调委托 OnReceivedCallback 设置为 item.OnReceived 方法,该方法
将有子类实现;在将当前订阅服务通道创建完成后,标记服务状态 started 为 true,防止重复启动;
同时,在该抽象类中,不实现契约的 OnReceived(MessageBody message);强制基础业务服务类去自我实现,因为各种业务的特殊性,这块
对消息的处理不能再基础服务中完成
public class MQServcieManager
{
public int Timer_tick { get; set; } = 10 * 1000;
private Timer timer = null;
public Action OnAction = null;
public MQServcieManager()
{
timer = new Timer(OnInterval, "", Timer_tick, Timer_tick);
}
///
/// 自检,配合 RabbitMQ 内部自动重连机制
///
///
private void OnInterval(object sender)
{
int error = 0, reconnect = 0;
OnAction?.Invoke(MessageLevel.Information, $"{DateTime.Now} 正在执行自检", null);
foreach (var item in this.Services)
{
for (int i = 0; i < item.Channels.Count; i++)
{
var c = item.Channels[i];
if (c.Connection == null || !c.Connection.IsOpen)
{
error++;
OnAction?.Invoke(MessageLevel.Information, $"{c.ExchangeName} {c.QueueName} {c.RoutekeyName} 重新创建订阅", null);
try
{
c.Stop();
var channel = item.CreateChannel(c.QueueName, c.RoutekeyName, c.ExchangeTypeName);
item.Channels.Remove(c);
item.Channels.Add(channel);
OnAction?.Invoke(MessageLevel.Information, $"{c.ExchangeName} {c.QueueName} {c.RoutekeyName} 重新创建完成", null);
reconnect++;
}
catch (Exception ex)
{
OnAction?.Invoke(MessageLevel.Information, ex.Message, ex);
}
}
}
}
OnAction?.Invoke(MessageLevel.Information, $"{DateTime.Now} 自检完成,错误数:{error},重连成功数:{reconnect}", null);
}
public void Start()
{
foreach (var item in this.Services)
{
try
{
item.Start();
}
catch (Exception e)
{
OnAction?.Invoke(MessageLevel.Error, $"启动服务出错 | {e.Message}", e);
}
}
}
public void Stop()
{
try
{
foreach (var item in this.Services)
{
item.Stop();
}
Services.Clear();
timer.Dispose();
}
catch (Exception e)
{
OnAction?.Invoke(MessageLevel.Error, $"停止服务出错 | {e.Message}", e);
}
}
public void AddService(IService service)
{
Services.Add(service);
}
public List Services { get; set; } = new List();
}
public enum MessageLevel
{
Trace = 0,
Debug = 1,
Information = 2,
Warning = 3,
Error = 4,
Critical = 5,
None = 6
}
终于来到了这一步,我们将要开始使用这个基础服务;首先,创建一个 DemoService 继承自 MQServiceBase ;
同时,实现 MQServiceBase 的抽象方法 OnReceived(MessageBody message)
public class DemoService : MQServiceBase
{
public Action OnAction = null;
public DemoService(MQConfig config) : base(config)
{
base.Queues.Add(new QueueInfo()
{
ExchangeType = ExchangeType.Direct,
Queue = "login-message",
RouterKey = "pk",
OnReceived = this.OnReceived
});
}
public override string vHost { get { return "gpush"; } }
public override string Exchange { get { return "user"; } }
///
/// 接收消息
///
///
public override void OnReceived(MessageBody message)
{
try
{
Console.WriteLine(message.Content);
}
catch (Exception ex)
{
OnAction?.Invoke(MessageLevel.Error, ex.Message, ex);
}
message.Consumer.Model.BasicAck(message.BasicDeliver.DeliveryTag, true);
}
}
public partial class QueueInfo
{
///
/// 队列名称
///
public string Queue { get; set; }
///
/// 路由名称
///
public string RouterKey { get; set; }
///
/// 交换机类型
///
public string ExchangeType { get; set; }
///
/// 接受消息委托
///
public Action OnReceived { get; set; }
///
/// 输出信息到客户端
///
public Action OnAction { get; set; }
}
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
MQConfig config = new MQConfig()
{
HostName = "127.0.0.1",
Password = "123456",
Port = 5672,
UserName = "dotnet"
};
MQServcieManager manager = new MQServcieManager();
manager.AddService(new DemoService(config));
manager.OnAction = OnActionOutput;
manager.Start();
Console.WriteLine("服务已启动");
Console.ReadKey();
manager.Stop();
Console.WriteLine("服务已停止,按任意键退出...");
Console.ReadKey();
}
static void OnActionOutput(MessageLevel level, string message, Exception ex)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0} | {1} | {2}", level, message, ex?.StackTrace);
Console.ForegroundColor = ConsoleColor.Gray;
}
}
在文章中,我们建立了 RabbitMQ 的通道管理、基础服务管理、契约实现等操作,让业务开发人员
通过简单的继承实现去快速的处理业务系统的逻辑,后续如果有增加消费者的情况下,只需要通过 MQServcieManager.AddService 进行简单的调用操作即可,无需对底层技术细节进行过多的改动。