程序员小王的博客:程序员小王的博客
欢迎点赞 收藏 ⭐留言
如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕
java自学的学习路线:java自学的学习路线
小提示:RabbitMQ通过三篇博客进行记录 1. RabbitMQ安装以及消息模型使用攻略 2. SpringBoot中使用RabbitMQ 3. MQ的应用场景 其中SpringBoot中使用RabbitMQ,MQ的应用场景将在明日发布
RabbitMQ(Rabbit Message queue)=消息中间件,是一种理念(规范),RabbitMQ是其中的一个落地产品
一、MQ引言 1、什么是MQ?MQ(Message Quene) : 翻译为 消息队列,通过典型的 生产者和消费者模型,生产者不断向消息队列中生产消息,消费者不断的从队列中获取消息。因为消息的生产和消费都是异步的,而且只关心消息的发送和接收,没有业务逻辑的侵入,轻松的实现系统间解耦。别名为 消息中间件 通过利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成。
消息队列:消息(数据),队列(排队) 先进先出
例: 订单系统(生产者),将数量这个数据给消息中间件,库存系统(消费者),消费消息中间件的数据
2、MQ有哪些?当今市面上有很多主流的消息中间件,如老牌的ActiveMQ、RabbitMQ,炙手可热的Kafka(大数据,高效,安全性低),阿里巴巴自主开发RocketMQ(OPPO 用的RocketMQ)等。
3、不同MQ的特点# 1. ActiveMQ JMS java13种规范(接口)之一(jdbc)
ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。
它是一个完全支持JMS规范的的消息中间件。丰富的API,
多种集群架构模式让ActiveMQ在业界成为老牌的消息中间件,在中小型企业颇受欢迎!
# 2. Kafka
Kafka是linkedIn开源的分布式发布-订阅消息系统,
目前归属于Apache顶级项目。Kafka主要特点是基于Pull的模式来处理消息消费,
追求高吞吐量,一开始的目的就是用于日志收集和传输。
0.8版本开始支持复制,不支持事务,对消息的重复、丢失、错误没有严格要求,
适合产生大量数据的互联网服务的数据收集业务。
# 3. RocketMQ
RocketMQ是阿里开源的消息中间件,
它是纯Java开发,具有高吞吐量、高可用性、适合大规模分布式系统应用的特点。
RocketMQ思路起源于Kafka,
但并不是Kafka的一个Copy,它对消息的可靠传输及事务性做了优化,
目前在阿里集团被广泛应用于交易、充值、流计算、消息推送、日志流式处理、binglog分发等场景。
# 4. RabbitMQ (安全)
RabbitMQ是使用Erlang语言开发的开源消息队列系统,
基于AMQP协议来实现。AMQP的主要特征是面向消息、队列、路由(包括点对点和发布/订阅)、可靠性、安全。
AMQP协议更多用在企业系统内对数据一致性、稳定性和可靠性要求很高的场景,对性能和吞吐量的要求还在其次。
RabbitMQ比Kafka可靠,Kafka更适合IO高吞吐的处理,一般应用在大数据日志处理或对实时性(少量延迟),可靠性(少量丢数据)要求稍低的场景使用,比如ELK日志收集。
二、RabbitMQ的引言 1、RabbitMQ官网
官网: https://www.rabbitmq.com/
官方教程: https://www.rabbitmq.com/#getstarted
基于AMQP协议,erlang语言开发,是部署最广泛的开源消息中间件,是最受欢迎的开源消息中间件之一。
2、AMQP协议AMQP(advanced message queuing protocol)先进的消息排队协议`在2003年时被提出,最早用于解决金融领域不同平台之间的消息传递交互问题。顾名思义,AMQP是一种协议,更准确的说是一种binary wire-level protocol(链接协议)。这是其和JMS的本质差别,AMQP不从API层进行限定,而是直接定义网络交换的数据格式。这使得实现了AMQP的provider天然性就是跨平台的。以下是AMQP协议模型:
Piblisher Application:生产者 Exchange:交换机 Virtual host:虚拟机 Message Queue:消息队列 Conbsumer Application:消费者3、RabbitMQ 的安装 (1)下载
官网下载地址: https://www.rabbitmq.com/download.html
(2)下载的安装包(3)安装步骤注意:这里的安装包是centos7安装的包
# 1.将rabbitmq安装包上传到linux系统中 erlang-22.0.7-1.el7.x86_64.rpm #erlang环境 socat-1.7.3.2-2.el7.x86_64.rpm #内存管理依赖 rabbitmq-server-3.7.18-1.el7.noarch.rpm
# 2.安装Erlang依赖包 rpm -ivh erlang-22.0.7-1.el7.x86_64.rpm rpm -ivh socat-1.7.3.2-2.el7.x86_64.rpm
# 3.安装RabbitMQ安装包(需要联网)
yum install -y rabbitmq-server-3.7.18-1.el7.noarch.rpm
注意:默认安装完成后配置文件模板在:
/usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example目录中,
需要将配置文件复制到/etc/rabbitmq/目录中,并修改名称为rabbitmq.config
# 4.复制配置文件 cp /usr/share/doc/rabbitmq-server-3.7.18/rabbitmq.config.example /etc/rabbitmq/rabbitmq.config
# 5.查看配置文件位置 ls /etc/rabbitmq/rabbitmq.config # 6.修改配置文件(参见下图:) :61 查看61行 vim /etc/rabbitmq/rabbitmq.config
# 7.执行如下命令,启动rabbitmq中的插件管理
rabbitmq-plugins enable rabbitmq_management
出现如下说明:
Enabling plugins on node rabbit@localhost:
rabbitmq_management
The following plugins have been configured:
rabbitmq_management
rabbitmq_management_agent
rabbitmq_web_dispatch
Applying plugin configuration to rabbit@localhost...
The following plugins have been enabled:
rabbitmq_management
rabbitmq_management_agent
rabbitmq_web_dispatch
set 3 plugins.
Offline change; changes will take effect at broker restart.
# 8.启动RabbitMQ的服务 systemctl start rabbitmq-server systemctl restart rabbitmq-server systemctl stop rabbitmq-server
注意:如果启动出现问题
Job for rabbitmq-server.service failed because the control process exited with error code
需要修改主机名
查看本机主机名
hostname
修改主机名
hostnamectl set-hostname 主机名
# 10.关闭防火墙服务
systemctl stop firewalld
systemctl disable firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
# 11.访问web管理界面( 192.168.5.128是我自己的ip地址) http:// 192.168.5.128:15672/
# 12.登录管理界面 默认的 username: guest password: guest
关闭RabbitMQ之后
systemctl stop rabbitmq-server
前端界面
4、RabbitMQ 配置# 1.服务启动相关 systemctl start|restart|stop|status rabbitmq-server # 2.管理命令行 用来在不使用web管理界面情况下命令操作RabbitMQ rabbitmqctl help 可以查看更多命令 # 3.插件管理命令行 rabbitmq-plugins enable|list|disable5、web管理界面介绍 (1)overview概览
connections:无论生产者还是消费者,都需要与RabbitMQ建立连接后才可以完成消息的生产和消费,在这里可以查看连接情况channels:通道,建立连接后,会形成通道,消息的投递获取依赖通道。Exchanges:交换机,用来实现消息的路由Queues:队列,即消息队列,消息存放在队列中,等待消费,消费后被移除队列。 (2)设置用户名和密码
上面的Tags选项,其实是指定用户的角色,可选的有以下几个:
超级管理员(administrator)
可登陆管理控制台,可查看所有的信息,并且可以对用户,策略(policy)进行操作。监控者(monitoring)
可登陆管理控制台,同时可以查看rabbitmq节点的相关信息(进程数,内存使用情况,磁盘使用情况等)策略制定者(policymaker)
可登陆管理控制台, 同时可以对policy进行管理。但无法查看节点的相关信息(上图红框标识的部分)。普通管理者(management)
仅可登陆管理控制台,无法看到节点信息,也无法对策略进行管理。其他
无法登陆管理控制台,通常就是普通的生产者和消费者。
(3)新建虚拟主机
虚拟主机:为了让各个用户可以互不干扰的工作,RabbitMQ添加了虚拟主机(Virtual Hosts)的概念。其实就是一个独立的访问路径,不同用户使用不同路径,各自有自己的队列、交换机,互相不会影响。
(4)绑定虚拟主机和用户创建好虚拟主机,我们还要给用户添加访问权限:
点击添加好的虚拟主机:
进入虚拟机设置界面:
设置成功后
三、RabbitMQ 的第一个程序 1、AMQP协议 2、RabbitMQ支持的消息模型 3、引入依赖RabitMQ的依赖
com.rabbitmq amqp-client 5.7.2
SpringBoot环境的依赖
4、第一种模型 (hello World)org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test com.rabbitmq amqp-client 5.7.2
六种模型跟着官网学,如果看不懂因为,使用谷歌浏览器翻译
在上图的模型中,有以下概念:
P(Provider):生产者,也就是要发送消息的程序C(Consumer):消费者:消息的接收者,会一直等待消息到来。queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。 (1)链接RabbitMQ
@Test
public void TestConnection() throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
System.out.println(connection);
connection.close();
}
(2)获取通道channel
public class TestHello {
// 生产者
@Test
public void provider() throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
System.out.println(connection);
//获取通道
Channel channel = connection.createChannel();
System.out.println(channel);
channel.close();
connection.close();
}
(3)开发生产者
// 生产者
@Test
public void provider() throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
System.out.println(connection);
//获取通道
Channel channel = connection.createChannel();
System.out.println(channel);
channel.queueDeclare("HelloQueues",false,false,false,null);
channel.basicPublish("","HelloQueues",null,"hello 2022".getBytes());
//关闭连接
channel.close();
connection.close();
}
注意:如果执行报错 连接超时异常 需要修改linux系统中 /etc/hosts文件
vim /etc/hosts
在127.0.0.1 此行最后加上主机名
(4)开发消费者
// 消费者
public static void main(String[] args) throws Exception {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
//获取通道
Channel channel = connection.createChannel();
channel.queueDeclare("HelloQueues", true, false, true, null);
channel.basicConsume("HelloQueues", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
System.out.println("消费者获取消息: " + message);
}
});
}
rabbitmq不支持更改现有名称的队列,如javaQueues,直接改为false是不可以的。也就是说rabbitmq不支持重新定义一个已存在的队列。
(5)设置队列长度HashMapmap = new HashMap<>(); map.put("x-max-length",5); //设置队列最大长度 //可以通过为x-overflow队列声明参数提供字符串值来设置溢出行为 。 //可能的值为drop-head(默认)或 reject-publish map.put("x-overflow","reject-publish"); channel.queueDeclare("javaQueues",true,false,true,map);
案例
@RunWith(SpringRunner.class)
//指定测试类启动时入口类的位置 //等价于指定工厂的位置
@SpringBootTest(classes = RabbitMQApplication.class)
public class TestHello {
// 生产者
// 生产者
@Test
public void provider() throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
System.out.println(connection);
//获取通道
Channel channel = connection.createChannel();
System.out.println(channel);
HashMap map = new HashMap<>();
map.put("x-max-length",5); //设置队列最大长度
//可以通过为x-overflow队列声明参数提供字符串值来设置溢出行为 。
//可能的值为drop-head(默认)或 reject-publish
//map.put("x-overflow","reject-publish");
//4、设置队列
channel.queueDeclare("helloQueues",true,false,true,map);
for (int i = 1; i < 11; i++) {
String s = "hello"+i;
//5、发布 生产消息
channel.basicPublish("","helloQueues",MessageProperties.PERSISTENT_TEXT_PLAIN,s.getBytes());
}
//关闭连接
channel.close();
connection.close();
}
// 消费者
public static void main(String[] args) throws Exception {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
//获取连接
Connection connection = factory.newConnection();
//获取通道
Channel channel = connection.createChannel();
HashMap map = new HashMap<>();
map.put("x-max-length",5); //设置队列最大长度
//可以通过为x-overflow队列声明参数提供字符串值来设置溢出行为 。
//可能的值为drop-head(默认)或 reject-publish
//map.put("x-overflow","reject-publish");
channel.queueDeclare("helloQueues", true, false, true, map);
channel.basicConsume("helloQueues", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
System.out.println("消费者获取消息: " + message);
}
});
}
}
5、封装RabbitMQ工具类
(1)RabbitMQ工具类
**
* @author 王恒杰
* @date 2022/1/21 16:10
* @Description:
*/
public class RabbitMQUtil {
private static ConnectionFactory factory = null;
static{
//创建连接工厂
factory = new ConnectionFactory();
//设置rabbitmq服务器IP地址
factory.setHost("192.168.5.128");
//设置rabbitmq服务器连接端口
factory.setPort(5672);
//设置rabbitmq服务器虚拟主机
factory.setVirtualHost("yingxue");
//设置rabbitmq服务器用户名
factory.setUsername("whj");
//设置rabbitmq服务器密码
factory.setPassword("563135");
}
//获取连接
public static Connection getConnection(){
Connection connection=null;
try {
connection= factory.newConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return connection;
}
//关闭资源
public static void close(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();
}
}
}
(2)生成者
public class Provider {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置队列
channel.queueDeclare("Hello_Util", true, false, true, null);
//产生发送数据 Publish出版
channel.basicPublish("", "Hello_Util", null, "hello王恒杰".getBytes());
//关闭资源
RabbitMQUtil.close(channel, connection);
}
}
(3)消费者
public class Consumer {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置队列
channel.queueDeclare("Hello_Util", true, false, true, null);
//消费者 消费信息
channel.basicConsume("Hello_Util", true,
//匿名内部类
new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
System.out.println("消费者获取消息: " + message);
}
});
}
}
5、第二种模型(work queue)
Work queues,也被称为(Task queues),任务模型。当消息处理比较耗时的时候,可能生产消息的速度会远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work 模型:让多个消费者绑定到一个队列,共同消费队列中的消息。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。
角色:
P:生产者:任务的发布者C1:消费者-1,领取任务并且完成任务,假设完成速度较慢C2:消费者-2:领取任务并完成任务,假设完成速度快 (1)开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
// //设置队列
channel.queueDeclare("Work_王恒杰",true,false,true,null);
//产生发送数据 Publish出版
for (int i = 0; i < 21; i++) {
String message="Work_王恒杰"+i;
channel.basicPublish("","Work_王恒杰",null,message.getBytes());
}
//关闭链接
RabbitMQUtil.close(channel,connection);
}
}
(2)开发消费者-1
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置队列
channel.queueDeclare("Work_王恒杰", true, false, true, null);
//获取消息
channel.basicConsume("Work_王恒杰",true,
//匿名内部类
new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
System.out.println("消费者1获取消息: " + message);
}
}
);
}
}
(3)开发消费者-2
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置队列
channel.queueDeclare("Work_王恒杰", true, false, true, null);
//获取消息
channel.basicConsume("Work_王恒杰",true,
//匿名内部类
new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
System.out.println("消费者1获取消息: " + message);
}
}
);
}
}
(4)测试结果
总结:默认情况下,RabbitMQ将按顺序将每个消息发送给下一个使用者。平均而言,每个消费者都会收到相同数量的消息。这种分发消息的方式称为循环。
(5)平均分配出现的问题让消费者1,睡眠1000毫秒再消费
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置队列
channel.queueDeclare("Work_王恒杰", true, false, true, null);
//获取消息
channel.basicConsume("Work_王恒杰",true,
//匿名内部类
new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
java.lang.String message = new String(body);
//打印消息前睡眠
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者1获取消息: " + message);
}
}
);
}
}
(6)消息自动确认机制
完成一项任务可能需要几秒钟。 您可能想知道,如果其中一个使用者开始一项漫长的任务并仅部分完成而死掉,会发生什么情况。 使用我们当前的代码,RabbitMQ一旦向消费者传递了一条消息,便立即将其标记为删除。 在这种情况下,如果您杀死一个工人,我们将丢失正在处理的消息。 我们还将丢失所有发送给该特定工作人员但尚未处理的消息。
但是我们不想丢失任何任务。 如果一个工人死亡,我们希望将任务交付给另一个工人。
channel.basicQos(1);//一次只接受一条未确认的消息
//参数2:关闭自动确认消息
channel.basicConsume("hello",false,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));
channel.basicAck(envelope.getDeliveryTag(),false);//手动确认消息
}
});
案例:让消费者1,睡眠1000毫秒再消费,消费者2不睡眠
生产者
消费者1
消费者2
测试结果
6、第三种模型(fanout)fanout 扇出 也称为广播
在广播模式下,消息发送流程是这样的:
可以有多个消费者每个消费者有自己的queue(队列)每个队列都要绑定到Exchange(交换机)生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定。交换机把消息发送给绑定过的所有队列队列的消费者都能拿到消息。实现一条消息被多个消费者消费 (1). 开发生产者
@author 王恒杰
* @date 2022/1/22 20:54
* @Description:
*/
public class Provider{
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置交换机参数 交换机名 交换机类型 持久化 自删 其他
channel.exchangeDeclare("fanout_王恒杰","fanout",true,true,null);
//发布消息 交换机名 路由key 基本属性 消息内容
channel.basicPublish("fanout_王恒杰","",null,"fonout_王恒杰。。。。".getBytes());
//关闭链接
RabbitMQUtil.close(channel, connection);
System.out.println("生成信息完成!");
}
}
(2).开发消费者-1
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//广播 一条消息多个消费者同时消费
//设置交换机参数 交换机名 交换机类型 持久化 自删 其他
channel.exchangeDeclare("fanout_王恒杰", "fanout", true, true, null);
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 临时队列名 交换机名 路由key
channel.queueBind(queue,"fanout_王恒杰","");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(3). 开发消费者-2
public class Consumer2 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//广播 一条消息多个消费者同时消费
//设置交换机参数 交换机名 交换机类型 持久化 自删 其他
channel.exchangeDeclare("fanout_王恒杰", "fanout", true, true, null);
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 临时队列名 交换机名 路由key
channel.queueBind(queue,"fanout_王恒杰","");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(4).开发消费者-3
public class Consumer3 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//广播 一条消息多个消费者同时消费
//设置交换机参数 交换机名 交换机类型 持久化 自删 其他
channel.exchangeDeclare("fanout_王恒杰", "fanout", true, true, null);
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 临时队列名 交换机名 路由key
channel.queueBind(queue,"fanout_王恒杰","");
//消费消息 临时队列名 是否自动应答 callback
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("消费者3: "+new String(body));
}
});
}
}
(5). 测试结果
7、Route 路由模型(订阅模型-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). 开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置交换机参数 交换机名 交换机类型(Direct(直连) 静态key)
channel.exchangeDeclare("exchange_王恒杰","direct");
//发布消息 交换机名 路由key 基本属性 消息内容
channel.basicPublish("exchange_王恒杰","user",null,"wxchange_direct_王恒杰。。。。".getBytes());
//关闭链接
RabbitMQUtil.close(channel, connection);
System.out.println("生成信息完成!");
}
}
(2).开发消费者-1
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//广播 一条消息多个消费者同时消费
//设置交换机参数 Direct(直连)
channel.exchangeDeclare("exchange_王恒杰", "direct");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 参数1:临时队列名 参数2:交换机名 参数3:交换机key(category:类别)
channel.queueBind(queue, "exchange_王恒杰", "category");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(3). 开发消费者-2
public class Consumer2 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//广播 一条消息多个消费者同时消费
//设置交换机参数 Direct(直连)
channel.exchangeDeclare("exchange_王恒杰", "direct");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 参数1:临时队列名 参数2:交换机名(category:类别) 参数3:交换机key
channel.queueBind(queue, "exchange_王恒杰", "user");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(4). 测试结果
消费者1
消费者2
8、Topic 订阅模型(动态路由模型)Topic类型的Exchange与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列。只不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符!这种模型Routingkey 一般都是由一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
通配符
* (star) can substitute for exactly one word. 匹配不多不少恰好1个词 # (hash) can substitute for zero or more words. 匹配一个或多个词 如: audit.* 只能匹配 audit.irs audit.# 可匹配audit.irs.corporate 或者 audit.irs 等(1). 开发生产者
public class Provider {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
Channel channel = connection.createChannel();
//设置交换机 参数1:交换机名称 参数2:交换机类型 topic 使用动态路由(通配符方式)
channel.exchangeDeclare("topic_王恒杰", "topic");
// 动态路由key
String routeKey = "user.save";
//发布消息 参数1:交换机名 参数2:路由key 参数3:是否持久化 参数4:消息内容
channel.basicPublish("topic_王恒杰", routeKey, null, ("这是路由的动态订阅模型,route key:[" + routeKey + "]").getBytes());
//关闭资源
RabbitMQUtil.close(channel, connection);
System.out.println("生产信息完成....");
}
}
(2).开发消费者-1
Routing Key中使用*通配符方式
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//设置交换机参数 参数1:交换机名称 参数2:交换机类型 topic 使用动态路由(通配符方式)
channel.exchangeDeclare("topic_王恒杰","topic");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 参数1:临时队列名 参数2:交换机名 参数3:动态路由key
channel.queueBind(queue, "topic_王恒杰", "user.*");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(3). 开发消费者-2
Routing Key中使用#通配符方式
public class Consumer2 {
public static void main(String[] args) throws IOException {
//获取链接
Connection connection = RabbitMQUtil.getConnection();
//创建通道
final Channel channel = connection.createChannel();
//设置交换机参数 参数1:交换机名称 参数2:交换机类型 topic 使用动态路由(通配符方式)
channel.exchangeDeclare("topic_王恒杰","topic");
//创建临时队列
String queue = channel.queueDeclare().getQueue();
//将临时队列绑定到exchange 参数1:临时队列名 参数2:交换机名 参数3:动态路由key
channel.queueBind(queue, "topic_王恒杰", "user.#");
//消费消息 临时队列名 是否自动应答 callback
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));
}
});
}
}
(4). 测试结果
消费者-1:Routing Key中使用*通配符方式
消费者-2:Routing Key中使用#通配符方式



