RabbitMQ支持的消息模型 https://www.rabbitmq.com/getstarted.html
环境搭建 创建一个Maven项目导入RabbitMQ依赖
1 2 3 4 5 6 <dependency > <groupId > com.rabbitmq</groupId > <artifactId > amqp-client</artifactId > <version > 5.7.2</version > </dependency >
创建ems
用户,密码为123
,创建VirtualHost /ems
Hello World 模型
在上图的模型中,有以下概念:
P:生产者,也就是要发送消息的程序
C:消费者:消息的接受者,会一直等待消息到来。
queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。
生产者 创建生产者Provider类,通过连接工厂对象获取连接,创建通道channel
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 public class Provider { @Test public void testSendMessage () throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost" ); connectionFactory.setPort(5672 ); connectionFactory.setVirtualHost("/ems" ); connectionFactory.setUsername("ems" ); connectionFactory.setPassword("123" ); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello" ,false ,false ,false ,null ); channel.basicPublish("" ,"hello" , null ,"hello rabbitmq" .getBytes()); channel.close(); connection.close(); } }
消费者 channel.queueDeclare();
与生产者保持一致,使用channel.basicConsume()
接收消息,回调接口new DefaultConsumer(channel)
重写handleDelivery()
方法
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 public class Customer { public static void main (String[] args) throws IOException, TimeoutException { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost" ); connectionFactory.setPort(5672 ); connectionFactory.setVirtualHost("/ems" ); connectionFactory.setUsername("ems" ); connectionFactory.setPassword("123" ); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello" , false , false , false , null ); channel.basicConsume("hello" , true , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("new String(body)=" + new String(body)); } }); } }
测速 首先启动消费者监听,然后在启动生产者发送消息。发送消息后消费者进行消费
参数说明 channel.queueDeclare("hello",false,false,false,null);
参数1:queue 队列名称 如果队列不存在则自动创建
参数2:durable 用来定义队列特性是否要持久化 true 持久化队列 false 不持久化
参数3:exclusive 是否独占队列 true 独占队列 false 不独占
参数4:autoDelete 是否在消费完成后自动删除队列 true 自动删除 false 不自动删除
channel.basicPublish("","aa", null,"hello rabbitmq".getBytes());
参数1:交换机名称
参数2:队列名称
参数3:传递消息额外设置
参数4;消息的具体内容
channel.basicConsume()
参数1:消费哪个队列的信息 队列名称
参数2:开启消息的自动确认机制
参数3:消费时的回调接口
durable为ture只能实现队列持久化。若想要其中未消费的消息持久化channel.basicPublish()
中参数3要设置为MessageProperties.PERSISTENT_TEXT_PLAIN
封装工具类 通过实现Hello World模型,我们可以发现存在了许多重复的代码。例如获取连接对象,关闭连接操作。我们将其封装成一个工具类 RabbitMQUtils
,获取连接对象getConnection()
,关闭资源closeConnectionAndChanel()
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 public class RabbitMQUtils { public static Connection getConnection () { try { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost" ); connectionFactory.setPort(5672 ); connectionFactory.setVirtualHost("/ems" ); connectionFactory.setUsername("ems" ); connectionFactory.setPassword("123" ); return connectionFactory.newConnection(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } return null ; } public static void closeConnectionAndChanel (Channel channel, Connection connection) { try { if (channel != null ) { channel.close(); } if (connection != null ) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } }
不过上述代码还是可以优化的,每次获取连接都需要创建一次工厂对象是没有必要的。相关认证资源也只需要加载一次即可。于是我们将代码优化
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 public class RabbitMQUtils { private static ConnectionFactory connectionFactory; static { connectionFactory = new ConnectionFactory(); connectionFactory.setHost("localhost" ); connectionFactory.setPort(5672 ); connectionFactory.setVirtualHost("/ems" ); connectionFactory.setUsername("ems" ); connectionFactory.setPassword("123" ); } public static Connection getConnection () { try { return connectionFactory.newConnection(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } return null ; } public static void closeConnectionAndChanel (Channel channel, Connection connection) { try { if (channel != null ) { channel.close(); } if (connection != null ) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } }
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 public class Provider { @Test public void testSendMessage () throws IOException, TimeoutException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello" ,true ,false ,false ,null ); channel.basicPublish("" ,"hello" , MessageProperties.PERSISTENT_TEXT_PLAIN,"hello rabbitmq" .getBytes()); RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
消费者同样使用工具类
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 public class Customer { public static void main (String[] args) throws IOException, TimeoutException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("hello" , true , false , false , null ); channel.basicConsume("hello" , true , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("new String(body)=" + new String(body)); } }); } }
封装成功!
Work Quene 模型 Work queues
,也被称为(Task queues
),任务模型。当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息 。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。
角色:
P:生产者:任务的发布者
C1:消费者-1,领取任务并且完成任务,假设完成速度较慢
C2:消费者-2:领取任务并完成任务,假设完成速度快
平均消费信息 生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Provider { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("work" ,true ,false ,false ,null ); for (int i = 1 ; i <= 20 ; i++) { channel.basicPublish("" ,"work" ,null ,(i+"hello work queue" ).getBytes()); } RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
消费者 消费者1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Customer1 { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("work" , true , false , false , null ); channel.basicConsume("work" , true , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者-1:" + new String(body)); } }); } }
消费者2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Customer2 { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.queueDeclare("work" , true , false , false , null ); channel.basicConsume("work" , true , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者-2:" + new String(body)); } }); } }
测速 先分别启动消费者1和消费者2进行监听,再启动生产者生产消息
可以看到20条消息被依次平均消费了,轮询。
不过这种消费效果会导致一种问题。当某一个消费者出现了故障或者消费消息的时间过长,则会导致整个队列的消息都会变慢。类似木桶效应,因此我们需要一种能者多劳多得的消费消息策略。
消息自动确认机制
Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the consumer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We’ll also lose all the messages that were dispatched to this particular worker but were not yet handled.
But we don’t want to lose any tasks. If a worker dies, we’d like the task to be delivered to another worker.
我们在channel.basicConsume()
中配置了消息自动确认。
不过开启自动确认机制还是存在隐患,例如上图消息消费者1接收到了5个消息后,自动确认了。则队列中的消息则会收到确认后删除。而消费者1消费3个消息后出现故障宕机,则为被消费的剩余两个消息则丢失了。
能者多劳多得
关闭自动确认 channel.basicConsume(队列名, false,回调函数)
道道每一次只消费一条信息 channel.basicQos(1);
消费消息后手动确认 channel.basicAck(envelope.getDeliveryTag(),false);
消费者
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 public class Customer1 { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.basicQos(1 ); channel.queueDeclare("work" , true , false , false , null ); channel.basicConsume("work" , false , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { try { Thread.sleep(2000 ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("消费者-1:" + new String(body)); channel.basicAck(envelope.getDeliveryTag(),false ); } }); } }
消费者1每次消费消息前先睡眠2秒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Customer2 { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.basicQos(1 ); channel.queueDeclare("work" , true , false , false , null ); channel.basicConsume("work" , false , new DefaultConsumer(channel) { @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者-2:" + new String(body)); channel.basicAck(envelope.getDeliveryTag(),false ); } }); } }
测试 两个消费者进行修改后,消费者1的消费速度远远小于消费者2 。此时看消费100条信息的结果。
消费者1只消费了1条消息,而消费者2消费了99条消息。实现了能者多劳多得多效果!
Fanout 模型 广播模型
角色:
在广播模式下,消息发送流程是这样的:
可以有多个消费者
每个消费者有自己的queue (队列)
每个队列都要绑定到Exchange (交换机)
生产者发送的消息,只能发送到交换机 ,交换机来决定要发给哪个队列,生产者无法决定。
交换机把消息发送给绑定过的所有队列
队列的消费者都能拿到消息。实现一条消息被多个消费者消费
生产者 声明交换机channel.exchangeDeclare("logs", "fanout");
参数1:交换机名称 参数2:交换机类型 fanout 广播类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Provider { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("logs" , "fanout" ); channel.basicPublish("logs" , "" , null , "fanout type message" .getBytes()); RabbitMQUtils.closeConnectionAndChanel(channel, connection); } }
消费者 消费者1
channel.exchangeDeclare("logs","fanout");
通道绑定交换机
String queue = channel.queueDeclare().getQueue();
获取临时队列
channel.queueBind(queue,"logs","");
绑定交换机和队列
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 public class Customer1 { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("logs" ,"fanout" ); String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue,"logs" ,"" ); channel.basicConsume(queue,true ,new DefaultConsumer(channel){ @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者1:" +new String(body)); } }); } }
消费者2和消费者3复制修改输入语句即可。
测试 首先启动消费者们,在启动生产者生产消息。
测试成功!
Direct 模型
在Fanout模式中,一条消息,会被所有订阅的队列都消费。但是,在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。
在Direct模型下:
队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey
(路由key)
消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey
。
Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key
进行判断,只有队列的Routingkey
与消息的 Routing key
完全一致,才会接收到消息
图解:
P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。
X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列
C1:消费者,其所在队列指定了需要routing key 为 error 的消息
C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息
生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Provider { public static void main (String[] args) throws IOException { String exchangeName = "logs_direct" ; Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName,"direct" ); String routingKey = "error" ; channel.basicPublish(exchangeName,routingKey,null ,("这是direct模型发布的基于routingKey:【" +routingKey+"】" ).getBytes()); RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
消费者 消费者1
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 public class Customer1 { public static void main (String[] args) throws IOException { String exchangeName = "logs_direct" ; Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName,"direct" ); String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue,exchangeName,"error" ); channel.basicConsume(queue,true ,new DefaultConsumer(channel){ @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者1:" +new String(body)); } }); } }
消费者2
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 public class Customer2 { public static void main (String[] args) throws IOException { String exchangeName = "logs_direct" ; Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName,"direct" ); String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue,exchangeName,"info" ); channel.queueBind(queue,exchangeName,"error" ); channel.queueBind(queue,exchangeName,"warning" ); channel.basicConsume(queue,true ,new DefaultConsumer(channel){ @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者2:" +new String(body)); } }); } }
测试 生产者发送消息是的routingKey为error
所以消费者1,和消费者2都能消费
当我们被生产者绑定当routingKey改为info
时,此时只有消费者2才能消费
测试成功!
Topic 模型
Topic
类型的Exchange
与Direct
相比,都是可以根据RoutingKey
把消息路由到不同的队列。只不过Topic
类型Exchange
可以让队列在绑定Routing key
的时候使用通配符!这种模型Routingkey
一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
生产者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Provider { public static void main (String[] args) throws IOException { Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare("topics" ,"topic" ); String routingKey = "user.save.find" ; channel.basicPublish("topics" ,routingKey,null ,("这里是topic动态路由模型,routingKey:【" +routingKey+"】" ).getBytes()); RabbitMQUtils.closeConnectionAndChanel(channel,connection); } }
消费者 消费者1
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 public class Customer1 { public static void main (String[] args) throws IOException { String exchangeName = "topics" ; Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName,"topic" ); String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue,exchangeName,"user.*" ); channel.basicConsume(queue,true ,new DefaultConsumer(channel){ @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者1:" +new String(body)); } }); } }
消费者2
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 public class Customer2 { public static void main (String[] args) throws IOException { String exchangeName = "topics" ; Connection connection = RabbitMQUtils.getConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(exchangeName,"topic" ); String queue = channel.queueDeclare().getQueue(); channel.queueBind(queue,exchangeName,"user.#" ); channel.basicConsume(queue,true ,new DefaultConsumer(channel){ @Override public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [] body) throws IOException { System.out.println("消费者2:" +new String(body)); } }); } }
测试 生产者绑定的routingKey为user.save.find
,消费者1的routingKey为user.*
,消费者2的routingKey为user.#
。所以只符合消费者2。
测试成功!