天不为人之恶寒也辍冬,地不为人之恶辽远也辍广。——《荀子》
常见名词
Virtual Hosts——虚拟主机,一个虚拟主机下可有多个队列
Exchange——交换机,分发消息到队列中
管理界面
使用默认账户guest密码guest登录RabbitMQ管理界面
这里可以看到我们的端口和相关信息
15672——管理界面
25672——RabbitMQ集群通信端口号
5672——RabbitMQ内部通信端口号
快速入门
引入依赖
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.10.0</version> </dependency>
简单队列
生产者
package com.ruben.mq.rabbitMQ.simple; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.nio.charset.StandardCharsets; public class Send { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); // 创建到服务器的连接 try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // 声明要发送的队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; // 发送消息 channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8)); System.out.println(" [x] Sent '" + message + "'"); } } }
消费者
package com.ruben.mq.rabbitMQ.simple; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DeliverCallback; public class Recv { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // 等待接收消息 channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages."); // 收到消息后 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received '" + message + "'"); }; channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { }); } }
我们可以在管理界面看到队列和消息情况
我们再创建一个Virtual Host,点击Add virtual host
我们点击这个Virtual Host
点击Set permission来设置权限
然后创建队列
这里Durable表示持久化到磁盘,Transient表示队列只在内存中存储
这样我们就可以在创建连接时指定Virtual Host了
MQ确保消息不丢失
生产者->MQ
Ack消息确认机制(MQ收到消息后同步或异步的方式通知生产者)
/** * @MethodName: ACKConfirmDemo * @Description: acknowledge Confirm Demo [同步等待RabbitMQ确认回调] * @Date: 2021/2/18 0018 19:46 * * * @author: <achao1441470436@gmail.com> * @param: [] * @returnValue: void */ private static void ACKConfirmDemo() throws Exception { try (Connection connection = RabbitMQConnection.getConnection(); // 设置channel Channel channel = connection.createChannel()) { // 消息 String msg = "Hino Supa"; // 选择ack确认模式 channel.confirmSelect(); // 发送消息 channel.basicPublish("", QUEUE_NAME, null, msg.getBytes(StandardCharsets.UTF_8)); System.out.println("消息投递成功"); // 同步等待回调 boolean result = channel.waitForConfirms(); if (result) { System.out.println("消息投递成功"); } else { System.out.println("消息投递失败"); } } }
事务形式
/** * @MethodName: transactionDemo * @Description: transaction Demo [事务模式,成功调用提交事务,失败(遇到异常)回滚] * @Date: 2021/2/18 0018 19:47 * * * @author: <achao1441470436@gmail.com> * @param: [] * @returnValue: void */ private static void transactionDemo() throws Exception { try (Connection connection = RabbitMQConnection.getConnection(); //2.设置channel Channel channel = connection.createChannel()) { try { // 消息 String msg = "Hino Supa"; // 选择事务模式 channel.txSelect(); // 发送消息 channel.basicPublish("", QUEUE_NAME, null, msg.getBytes(StandardCharsets.UTF_8)); // 提交事务 channel.txCommit(); System.out.println("消息投递成功"); } catch (IOException e) { // 回滚 channel.txRollback(); e.printStackTrace(); } } }
MQ->消费
RabbitMQ必须要将消息消费成功后才会从mq服务端中移除
Kafka不管是消费成功还是失败,都不会立即从mq服务端中移除,使用offset记录消息消费情况
工作队列
我们的消费者可根据自身能力调整消费消息数,如果有多个消费者,则每次消费完成都去告诉RabbitMQ,从而获取下一条/多条消息
// 1.创建连接 Connection connection = RabbitMQConnection.getConnection(); // 2.设置通道 Channel channel = connection.createChannel(); // 3.设置每次获取消息数量 channel.basicQos(2); DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String msg = new String(body, StandardCharsets.UTF_8); System.out.println("消费者获取消息:" + msg); // 消费者完成 消费者通知给mq服务器端删除该消息 channel.basicAck(envelope.getDeliveryTag(), false); } }; // 3.监听队列 channel.basicConsume(QUEUE_NAME, false, defaultConsumer);
发布订阅
Exchange——交换机,分发消息到队列中
有以下几种交换机direct,topic,headers和fanout。
Fanout Exchange:扇形交换机——我们每个消费者都能收到消息
生产者代码
package com.ruben.mq.rabbitMQ.subcrible; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.ruben.mq.rabbitMQ.connection.RabbitMQConnection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class ProducerFanout { /** * 定义交换机的名称 */ private static final String EXCHANGE_NAME = "fanout_exchange"; public static void main(String[] args) throws IOException, TimeoutException { // 创建Connection try (Connection connection = RabbitMQConnection.getConnection(); // 创建Channel Channel channel = connection.createChannel();) { // 通道关联交换机(新版[5.10.0]自动创建交换机) channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true); String msg = "ruben"; // 发消息 channel.basicPublish(EXCHANGE_NAME, "", null, msg.getBytes()); } } }
消费者1
package com.ruben.mq.rabbitMQ.subcrible; import com.rabbitmq.client.*; import com.ruben.mq.rabbitMQ.connection.RabbitMQConnection; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeoutException; public class MailConsumer { /** * 定义邮件队列 */ private static final String QUEUE_NAME = "fanout_email_queue"; /** * 定义交换机的名称 */ private static final String EXCHANGE_NAME = "fanout_exchange"; public static void main(String[] args) throws IOException, TimeoutException { System.out.println("邮件消费者..."); // 创建我们的连接 Connection connection = RabbitMQConnection.getConnection(); // 创建我们通道 Channel channel = connection.createChannel(); // 关联队列消费者关联队列 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ""); DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String msg = new String(body, StandardCharsets.UTF_8); System.out.println("邮件消费者获取消息:" + msg); } }; // 开始监听消息 自动签收 channel.basicConsume(QUEUE_NAME, true, defaultConsumer); } }
消费者2
package com.ruben.mq.rabbitMQ.subcrible; import com.rabbitmq.client.*; import com.ruben.mq.rabbitMQ.connection.RabbitMQConnection; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeoutException; public class SmsConsumer { /** * 定义短信队列 */ private static final String QUEUE_NAME = "fanout_email_sms"; /** * 定义交换机的名称 */ private static final String EXCHANGE_NAME = "fanout_exchange"; public static void main(String[] args) throws IOException, TimeoutException { System.out.println("短信消费者..."); // 创建我们的连接 Connection connection = RabbitMQConnection.getConnection(); // 创建我们通道 final Channel channel = connection.createChannel(); // 关联队列消费者关联队列 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ""); DefaultConsumer defaultConsumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String msg = new String(body, StandardCharsets.UTF_8); System.out.println("短信消费者获取消息:" + msg); } }; // 开始监听消息 自动签收 channel.basicConsume(QUEUE_NAME, true, defaultConsumer); } }
springboot-RabbitMQ发送短信 2:https://developer.aliyun.com/article/1377334











