什么是RabbitMQ
RabbitMQ是一个开源的,基于AMQP(Advanced Message Queuing Protocol)协议的完整,可复用的企业级消息队列(Message Queue 一种应用程序与应用程序之间的一种通信方法)系统,RabbitMQ可以实现点对点,发布订阅等消息处理模式
使用 RabbitMQ
RabbitMQ从信息接收者角度可以看做三种模式:
- 一对一(简单队列模式)
- 一对多(是Worker模式 此一对多并不是发布订阅,而是每条信息只有一个接收者)
- 发布订阅(包括发布订阅模式,路由模式和通配符模式,可以总结为都是使用只是交换机(Exchange)类型不一致)
代码示例
简单模式
- 首先,我们需要创建两个控制台项目.Send(发送者)和Receive(接收者),然后为两个项目安装RabbitMQ.Client驱动
install-package rabbitmq.client
- 然后在Send和Receive项目中编写我们的消息队列代码
- 发送者代码
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
| using RabbitMQ.Client; using System; using System.Text;
namespace HelloWorldRabbitMQ.Send { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory conFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection con = conFactory.CreateConnection()) { using (IModel channel = con.CreateModel()) { String queryName = "queue1"; channel.QueueDeclare( queue: queryName, durable: false, exclusive: false, autoDelete: false, arguments: null ); while (true) { Console.WriteLine("消息内容"); string message = Console.ReadLine(); byte[] body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "", routingKey: queryName, basicProperties: null, body: body); Console.WriteLine("成功发送消息:" + message); } } } } } }
|
可以看到RabbitMQ使用了IConnectionFactory,IConnection和IModel来创建链接和通信管道,IConnection实例对象只负责与Rabbit的连接,而发送接收这些实际操作全部由会话通道进行,而后使用QueneDeclare方法进行创建消息队列,创建完成后可以在RabbitMQ的管理工具中看到此队列,QueneDelare方法需要一个消息队列名称的必须参数.后面那些参数则代表缓存,参数等信息.最后使用BasicPublish来发送消息,在一对一中routingKey必须和 queueName一致
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
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text;
namespace HelloWorldRabbitMQ.Receive { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String queueName = String.Empty; if (args.Length > 0) queueName = args[0]; else queueName = "queue1"; channel.QueueDeclare( queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null ); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); }; channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer); Console.ReadKey(); } } }
} }
|
在接收者中是定义一个EventingBasicConsumer对象的消费者(接收者),这个消费者与会话对象关联,
然后定义接收事件,输出从消息队列中接收的数据,
最后使用会话对象的BasicConsume方法来启动消费者监听.消费者的定义也是如此简单.
不过注意一点,可以看到在接收者代码中也有声明队列的方法,其实这句代码可以去掉,但是如果去掉的话接收者在程序启动时监听队列,而此时这个队列还未存在,所以会出异常,所以往往会在消费者中也添加一个声明队列方法
此时,简单消息队列传输就算写好了,我们可以运行代码就行测试
Worker模式
Worker模式其实是一对多的模式,但是这个一对多并不是像发布订阅那种,而是信息以顺序的传输给每个接收者,我们可以使用上个例子来运行worker模式甚至,只需要运行多个接收者即可
可以看到运行两个接收者,然后发送者发送了1-5这五个消息,第一个接收者接收的是奇数,而第二个接收者接收的是偶数,但是现在的worker存在这很大的问题,
丢失数据:一旦其中一个宕机,那么另外接收者的无法接收原本这个接收者所要接收的数据
无法实现能者多劳:如果其中的接收者接收的较慢,那么便会极大的浪费性能,所以需要实现接收快的多接收
下面针对上面的两个问题进行处理
首先我们先来看一下所说的宕机丢失数据一说,我们在上个例子Receive接收事件中添加线程等待
1 2 3 4 5 6
| consumer.Received += (model, ea) => { Thread.Sleep(1000); byte[] message = ea.Body; Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); };
|
然后再次启动三个接收者进行测试
可以看到发送者发送了1-9的数字,第二个接收者在接收数据途中宕机,第一个接收者也并没有去接收第二个接收者宕机后的数据,有的时候我们会有当接收者宕机后,其余数据交给其它接收者进行消费,那么该怎么进行处理呢,解决这个问题得方法就是改变其消息确认模式
在Rabbit中存在两种消息确认模式
自动确认:只要消息从队列获取,无论消费者获取到消息后是否成功消费,都认为是消息成功消费,也就是说上面第二个接收者其实已经消费了它所接收的数据
手动确认:消费从队列中获取消息后,服务器会将该消息处于不可用状态,等待消费者反馈
也就是说我们只要将消息确认模式改为手动即可,改为手动确认方式只需改两处,1.开启监听时将autoAck参数改为false,2.消息消费成功后返回确认
1 2 3 4 5 6 7 8 9 10 11
| consumer.Received += (model, ea) => { Thread.Sleep(1000); byte[] message = ea.Body; Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
|
然后再次测试便会出现完全接收的结果
能者多劳是建立在手动确认基础上,下面修改一下代码中等待的时间
1 2 3 4 5 6 7 8
| consumer.Received += (model, ea) => { Thread.Sleep((new Random().Next(1,6))*1000); byte[] message = ea.Body; Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); };
|
然后只需要再添加BasicQos方法即可
1 2 3 4 5 6 7 8 9 10
| channel.QueueDeclare( queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null );
channel.BasicQos(0, 1, false);
|
运行看效果 可以看到此时已实现能者多劳
worker模式接收者完整代码
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
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading;
namespace HelloWorldRabbitMQ.Receive { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String queueName = String.Empty; if (args.Length > 0) queueName = args[0]; else queueName = "queue1"; channel.QueueDeclare( queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null ); channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { Thread.Sleep((new Random().Next(1, 6)) * 1000); byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); Console.ReadKey(); } } }
} }
|
Exchange模式(发布订阅模式,路由模式,通配符模式)
前面说过发布,路由,通配符这三种模式其实可以算为一种模式,区别仅仅是交互机类型不同.在这里出现了一个交换机的东西,发送者将消息发送发送到交换机,接收者创建各自的消息队列绑定到交换机
通过上面三幅图可以看出这三种模式本质就是一种订阅模式,路由,通配符模式只是订阅模式的变种模式。使其可以选择发送订阅者中的接收者。
注意:交换机本身并不存储数据,数据存储在消息队列中,所以如果向没有绑定消息队列的交换机中发送信息,那么信息将会丢失
下面依次来看一下这三种模式
发布订阅模式(fanout)
发送者代码
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
| using RabbitMQ.Client; using System; using System.Text;
namespace HelloWorldRabbitMQ.fanoutSend { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = String.Empty; if (args.Length > 0) exchangeName = args[0]; else exchangeName = "exchange1"; channel.ExchangeDeclare(exchange: exchangeName, type: "fanout"); while (true) { Console.WriteLine("消息内容:"); String message = Console.ReadLine(); byte[] body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: exchangeName, routingKey: "", basicProperties: null, body: body); Console.WriteLine("成功发送消息:" + message); } } } } }
}
|
发送者代码与上面没有什么差异,只是由上面的消息队列声明变成了交换机声明(交换机类型为fanout),也就说发送者发送消息从原来的直接发送消息队列变成了发送到交换机
接收者代码
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
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text;
namespace HelloWorldRabbitMQ.fanoutReceive { class Program { static void Main(string[] args) { int random = new Random().Next(1, 1000); Console.WriteLine("Start" + random.ToString()); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = String.Empty; if (args.Length > 0) exchangeName = args[0]; else exchangeName = "exchange1"; channel.ExchangeDeclare(exchange: exchangeName, type: "fanout"); String queueName = exchangeName + "_" + random.ToString(); channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: ""); channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); Console.ReadKey(); } } } } }
|
可以看到接收者代码与上面有些差异
路由模式(direct)
上面说过路由模式是订阅模式的一个变种模式,以路由进行匹配发送,例如将消息1发送给A,B两个消息队列,或者将消息2发送给B,C两个消息队列,路由模式的交换机是direct
发送者代码
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
| using RabbitMQ.Client; using System; using System.Text;
namespace HelloWorldRabbitMQ.directSend { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = "exchange2"; String routeKey = args[0]; channel.ExchangeDeclare(exchange: exchangeName, type: "direct"); while (true) { Console.WriteLine("消息内容:"); String message = Console.ReadLine(); byte[] body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: exchangeName, routingKey: routeKey, basicProperties: null, body: body); Console.WriteLine("成功发送消息:" + message); } } } } } }
|
发送者代码相比上面只改了两处
将交换机类型改为了direct类型
将运行时的第一个参数改成了路由名称,然后发送数据时由指定路由的消息队列进行获取数据
接收者代码
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
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text;
namespace HelloWorldRabbitMQ.directReceive { class Program { static void Main(string[] args) { if (args.Length == 0) throw new ArgumentException("args"); int random = new Random().Next(1, 1000); Console.WriteLine("Start" + random.ToString()); IConnectionFactory connFactory = new ConnectionFactory { HostName = "47.104.206.56", Port = 5672, UserName = "yan", Password = "yan" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = "exchange2"; channel.ExchangeDeclare(exchange: exchangeName, type: "direct"); String queueName = exchangeName + "_" + random.ToString(); channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); foreach (var routeKey in args) { channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: routeKey); } channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); Console.ReadKey(); } } } } }
|
在接收者代码中的改动点也是与发送者一致,但是一个接收者消息队列可以声明多个路由与交换机进行绑定
运行情况如下
通配符模式(topic)
通配符模式与路由模式一致,只不过通配符模式中的路由可以声明为模糊查询,RabbitMQ拥有两个通配符
注意:RabbitMQ中通配符并不像正则中的单个字符,而是一个以“.”分割的字符串,如 ”topic1.*“匹配的规则以topic1开始并且”.”后只有一段语句的路由 例:“topic1.aaa”,“topic1.bb”
发送者代码
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
| using RabbitMQ.Client; using System; using System.Text;
namespace HelloWorldRabbitMQ.topicSend { class Program { static void Main(string[] args) { Console.WriteLine("Start"); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = "exchange3"; String routeKey = args[0]; channel.ExchangeDeclare(exchange: exchangeName, type: "topic"); while (true) { Console.WriteLine("消息内容:"); String message = Console.ReadLine(); byte[] body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: exchangeName, routingKey: routeKey, basicProperties: null, body: body); Console.WriteLine("成功发送消息:" + message); } } } } } }
|
修改了两点:交换机名称(每个交换机只能声明一种类型,如果还用exchang2的话就会出异常),交换机类型改为topic
接收者代码
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
| using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text;
namespace HelloWorldRabbitMQ.topicRecoive { class Program { static void Main(string[] args) { if (args.Length == 0) throw new ArgumentException("args"); int random = new Random().Next(1, 1000); Console.WriteLine("Start" + random.ToString()); IConnectionFactory connFactory = new ConnectionFactory { HostName = "192.168.1.37", Port = 5672, UserName = "sa", Password = "Sa123456" }; using (IConnection conn = connFactory.CreateConnection()) { using (IModel channel = conn.CreateModel()) { String exchangeName = "exchange3"; channel.ExchangeDeclare(exchange: exchangeName, type: "topic"); String queueName = exchangeName + "_" + random.ToString(); channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); foreach (var routeKey in args) { channel.QueueBind(queue: queueName, exchange: exchangeName, routingKey: routeKey); } channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { byte[] message = ea.Body.ToArray(); Console.WriteLine("接收到信息为:" + Encoding.UTF8.GetString(message)); channel.BasicAck(ea.DeliveryTag, true); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); Console.ReadKey(); } } } } }
|
接收者修改与发送者一致
运行结果如下
参考:
https://www.cnblogs.com/yan7/p/9498685.html