近期项目里有需要用到RabbitMq实现一些业务,学习整理之后在此记录一下,如有问题或者不对的地方,欢迎留言指正。
一、首先创建连接工厂
public class RabbitMQProvider
{
private readonly string _ipAddress;
private readonly int? _port;
private readonly string _username;
private readonly string _password;
public RabbitMQProvider()
{
_ipAddress = ConfigurationHelper.GetKey("RabbitMQIPAddress") ?? throw new ArgumentException("IP地址未配置!");
_username = ConfigurationHelper.GetKey("RabbitMQUserName") ?? throw new ArgumentException("用户名不能为空");
_password = ConfigurationHelper.GetKey("RabbitMQPassword") ?? throw new ArgumentException("密码不能为空");
var timeApan = new TimeSpan(0, 5, 0);
if (ConnectionFactory == null)
{
ConnectionFactory = new ConnectionFactory//创建连接工厂对象
{
HostName = _ipAddress,//IP地址
UserName = _username,//用户账号
Password = _password,//用户密码
//启用自动连接恢复
AutomaticRecoveryEnabled = true,
//VirtualHost = "/mqtest",//RabbitMQ中要请求的VirtualHost名称
ContinuationTimeout = timeApan,
HandshakeContinuationTimeout = timeApan,
RequestedConnectionTimeout = timeApan,
SocketReadTimeout = timeApan,
SocketWriteTimeout = timeApan,
//启用异步消费
DispatchConsumersAsync = true,
//RequestedChannelMax = 5000
};
}
}
public ConnectionFactory ConnectionFactory { get; }
private static IConnection connection;
/// <summary>
/// 获取RabbitMQ连接对象方法(创建与RabbitMQ的连接)
/// </summary>
/// <returns></returns>
public IConnection GetConnection()
{
if (connection == null || !connection.IsOpen)
{
//通过工厂创建连接对象
connection = ConnectionFactory.CreateConnection();
}
return connection;
}
int times = 0;
private static IModel Channel;
public IModel GetChannel()
{
if (Channel != null)
return Channel;
else
{
//times++;
// Console.WriteLine($"CreateModel{times}次");
return GetConnection().CreateModel();
}
}
}
二、消息发布
1、获取连接、交换机和队列
public class RabbitMQPublisher : IPublisher
{
static int x_message_ttl;
static RabbitMQPublisher()
{
int.TryParse(ConfigurationHelper.GetKey("RabbitMQ_x-message-ttl"), out x_message_ttl);
x_message_ttl = x_message_ttl * 60 * 1000;
}
#region
private readonly RabbitMQProvider _provider;
private IConnection _connection;
public RabbitMQPublisher(RabbitMQProvi

本文详细介绍了如何在.NET项目中使用RabbitMQ,包括创建连接工厂、设置连接超时、发布消息(同步与批量)、消息订阅以及注意事项,涉及IModel和事件驱动的消费者模型。
最低0.47元/天 解锁文章
419

被折叠的 条评论
为什么被折叠?



