消息队列概述
MQ全称为Message Queue,消息队列是应用程序和应用程序之间的通信方法。在项目中,可将一些无需即时返回且耗时的操作提取出来,进行异步处理,而这种异步处理的方式大大的节省了服务器的请求响应时间,从而提高了系统的吞吐量。实现MQ的大致有两种主流方式:AMQP、JMS。
- AMQP是一种协议,更准确的说是一种binary wire-level protocol(链接协议)。这是其和JMS的本质差别,AMQP不从API层进行限定,而是直接定义网络交换的数据格式。
- JMS即Java消息服务(JavaMessage Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。
市场上常见的消息队列有如下:
- ActiveMQ:基于JMS
- ZeroMQ:基于C语言开发
- RabbitMQ:基于AMQP协议,erlang语言开发,稳定性好
- RocketMQ:基于JMS,阿里巴巴产品
- Kafka:类似MQ的产品;分布式消息系统,高吞吐量
RabbitMQ是由erlang语言开发,基于AMQP(Advanced Message Queue 高级消息队列协议)协议实现的消息队列,它是一种应用程序之间的通信方法,消息队列在分布式系统开发中应用非常广泛。
RabbitMQ官方地址:http://www.rabbitmq.com/
RabbitMQ提供了6种模式:简单模式,work模式,Publish/Subscribe发布与订阅模式,Routing路由模式,Topics主题模式,RPC远程调用模式。
官网对应模式介绍:https://www.rabbitmq.com/getstarted.html
RabbitMq入门工程搭建(简单模式实现)
1、创建maven工程,导入依赖
<dependencies>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
</dependencies>
2、编写提供者代码
package com.zzy.simple;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
static String Quene_name="simple";
public static void main(String[] args) throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
Connection connection = connectionFactory.newConnection();
//3、获取频道
Channel channel = connection.createChannel();
//4、创建队列
/**
* 参数:
* 队列名
* 是否持久化
* 是否独占资源
* 是否程序停止时自动删除队列数据
* 其他参数
*/
channel.queueDeclare(Quene_name, true, false, false, null);
//设置要发送的消息
String message="hello";
/**
* 参数:
* 交换机名称,没有指定就使用默认的
*路由key,简单模式可以使用队列名
* 消息其他属性
* 要发送的消息
*/
channel.basicPublish("",Quene_name,null,message.getBytes());
//关闭资源
channel.close();
connection.close();
}
}
3、编写获取连接工具类:
package com.zzy.util;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class ConnectionUtil {
public static Connection getConnection() throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
return connectionFactory.newConnection();
}
}
4、编写消费者代码
package com.zzy.simple;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Consumer {
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(Producer.Quene_name,true,false,false,null);
//创建消费者,并设置消息处理
DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("交换机为" + envelope.getExchange());
System.out.println("路由key为" + envelope.getRoutingKey());
System.out.println("消息id为"+envelope.getDeliveryTag());
System.out.println("发送的消息"+new String(body,"utf-8"));
}
};
//监听队列
/**
* 参数:
* 监听的队列名
* 是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name,true,defaultConsumer);
}
}
工作队列模式
提供者发送消息队列,多个消费者之间为竞争关系
需求:提供者提供30条消息,两个消费者接收数据
提供者代码:
package com.zzy.work;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
static String Quene_name="work";
public static void main(String[] args) throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
Connection connection = connectionFactory.newConnection();
//3、获取频道
Channel channel = connection.createChannel();
//4、创建队列
/**
* 参数:
* 队列名
* 是否持久化
* 是否独占资源
* 是否程序停止时自动删除队列数据
* 其他参数
*/
channel.queueDeclare(Quene_name, true, false, false, null);
//设置要发送的消息
for (int i = 1; i <= 30; i++) {
String message="hello"+i;
/**
* 参数:
* 交换机名称,没有指定就使用默认的
*路由key,简单模式可以使用队列名
* 消息其他属性
* 要发送的消息
*/
channel.basicPublish("",Quene_name,null,message.getBytes());
}
//关闭资源
channel.close();
connection.close();
}
}
消费者(可复制多个)
package com.zzy.work;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtil.getConnection();
final Channel channel = connection.createChannel();
channel.queueDeclare(Producer.Quene_name,true,false,false,null);
//一次只能接收并处理一个消息
channel.basicQos(2);
//创建消费者,并设置消息处理
DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
try {
System.out.println("交换机为" + envelope.getExchange());
System.out.println("路由key为" + envelope.getRoutingKey());
System.out.println("消息id为"+envelope.getDeliveryTag());
System.out.println("1接收的消息"+new String(body,"utf-8"));
Thread.sleep(1000);
//确认消息
channel.basicAck(envelope.getDeliveryTag(), false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
//监听队列
/**
* 参数:
* 监听的队列名
* 是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name,true,defaultConsumer);
}
}
测试时先启动消费者工程再启动提供者工程
发布与订阅模式
1、每个消费者监听自己的队列。
2、生产者将消息发给broker,由交换机将消息转发到绑定此交换机的每个队列,每个绑定交换机的队列都将接收到消息
提供者代码:
package com.zzy.fanout;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
static String Quene_name1="fanout1";
static String Quene_name2="fanout2";
static String Exchange_name="fanout";
public static void main(String[] args) throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
Connection connection = connectionFactory.newConnection();
//3、获取频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Exchange_name, BuiltinExchangeType.FANOUT);
//4、创建队列
/**
* 参数:
* 队列名
* 是否持久化
* 是否独占资源
* 是否程序停止时自动删除队列数据
* 其他参数
*/
channel.queueDeclare(Quene_name1, true, false, false, null);
channel.queueDeclare(Quene_name2, true, false, false, null);
//绑定队列与交换机
channel.queueBind(Quene_name1,Exchange_name,"");
channel.queueBind(Quene_name2,Exchange_name,"");
//设置要发送的消息
for (int i = 1; i <= 10; i++) {
String message="hello"+i;
/**
* 参数:
* 交换机名称,没有指定就使用默认的
* 路由key,简单模式可以使用队列名
* 消息其他属性
* 要发送的消息
*/
channel.basicPublish(Exchange_name,"",null,message.getBytes());
}
//关闭资源
channel.close();
connection.close();
}
}
消费者代码:
package com.zzy.fanout;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) throws Exception {
//创建连接
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Producer.Exchange_name,BuiltinExchangeType.FANOUT);
// 声明(创建)队列
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列
* 参数3:是否独占本次连接
* 参数4:是否在不使用的时候自动删除队列
* 参数5:队列其它参数
*/
channel.queueDeclare(Producer.Quene_name1, true, false, false, null);
//队列绑定交换机
channel.queueBind(Producer.Quene_name1, Producer.Exchange_name, "");
//创建消费者;并设置消息处理
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
/**
* consumerTag 消息者标签,在channel.basicConsume时候可以指定
* envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* properties 属性信息
* body 消息
*/
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由key
System.out.println("路由key为:" + envelope.getRoutingKey());
//交换机
System.out.println("交换机为:" + envelope.getExchange());
//消息id
System.out.println("消息id为:" + envelope.getDeliveryTag());
//收到的消息
System.out.println("消费者1-接收到的消息为:" + new String(body, "utf-8"));
}
};
//监听消息
/**
* 参数1:队列名称
* 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 参数3:消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name1, true, consumer);
}
}
路由模式
Exchange不再把消息交给每一个绑定的队列,而是根据消息的Routing Key 进行判断,只有队列的Routingkey 与消息的 Routing key 完全一致,才会接收到消息
实现需求:生产者发出两个队列分别绑定insert、update路由,两个消费者接收数据
提供者代码:
package com.zzy.direct;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
static String Quene_name1="insert";
static String Quene_name2="update";
static String Exchange_name="direct";
public static void main(String[] args) throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
Connection connection = connectionFactory.newConnection();
//3、获取频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Exchange_name, BuiltinExchangeType.DIRECT);
//4、创建队列
/**
* 参数:
* 队列名
* 是否持久化
* 是否独占资源
* 是否程序停止时自动删除队列数据
* 其他参数
*/
channel.queueDeclare(Quene_name1, true, false, false, null);
channel.queueDeclare(Quene_name2, true, false, false, null);
//绑定队列与交换机
channel.queueBind(Quene_name1,Exchange_name,"insert");
channel.queueBind(Quene_name2,Exchange_name,"update");
//设置要发送的消息
String message="hello";
/**
* 参数:
* 交换机名称,没有指定就使用默认的
* 路由key,简单模式可以使用队列名
* 消息其他属性
* 要发送的消息
*/
channel.basicPublish(Exchange_name,"insert",null,(message+"insert").getBytes());
channel.basicPublish(Exchange_name,"update",null,(message+"update").getBytes());
//关闭资源
channel.close();
connection.close();
}
}
消费者代码:
package com.zzy.direct;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) throws Exception {
//创建连接
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Producer.Exchange_name,BuiltinExchangeType.DIRECT);
// 声明(创建)队列
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列
* 参数3:是否独占本次连接
* 参数4:是否在不使用的时候自动删除队列
* 参数5:队列其它参数
*/
channel.queueDeclare(Producer.Quene_name1, true, false, false, null);
//队列绑定交换机
channel.queueBind(Producer.Quene_name1, Producer.Exchange_name, "insert");
//创建消费者;并设置消息处理
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
/**
* consumerTag 消息者标签,在channel.basicConsume时候可以指定
* envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* properties 属性信息
* body 消息
*/
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由key
System.out.println("路由key为:" + envelope.getRoutingKey());
//交换机
System.out.println("交换机为:" + envelope.getExchange());
//消息id
System.out.println("消息id为:" + envelope.getDeliveryTag());
//收到的消息
System.out.println("消费者1-接收到的消息为:" + new String(body, "utf-8"));
}
};
//监听消息
/**
* 参数1:队列名称
* 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 参数3:消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name1, true, consumer);
}
}
通配符模式
Topic 类型与Direct 相比,都是可以根据RoutingKey 把消息路由到不同的队列。只不过Topic 类型Exchange 可以让队列在绑定Routing key 的时候使用通配符。Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
通配符规则:
#:匹配一个或多个词
*:匹配一个单词
举例:
item.# :能够匹配item.insert.abc 或者 item.insert
item.* :只能匹配item.insert
生产者代码:
package com.zzy.topic;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
static String Quene_name1="insert";
static String Quene_name2="update";
static String Exchange_name="topic";
public static void main(String[] args) throws IOException, TimeoutException {
//1、创建连接工厂并设置参数
ConnectionFactory connectionFactory = new ConnectionFactory();
//设置主机地址,默认是localhost
connectionFactory.setHost("localhost");
//设置端口号,默认是5672
connectionFactory.setPort(5672);
//设置用户名,默认是guest
connectionFactory.setUsername("guest");
//设置密码,默认是guest
connectionFactory.setPassword("guest");
//设置虚拟主机名称,默认是"/"
connectionFactory.setVirtualHost("/");
//2、创建连接
Connection connection = connectionFactory.newConnection();
//3、获取频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Exchange_name, BuiltinExchangeType.TOPIC);
//设置要发送的消息
String message="hello";
/**
* 参数:
* 交换机名称,没有指定就使用默认的
* 路由key,简单模式可以使用队列名
* 消息其他属性
* 要发送的消息
*/
channel.basicPublish(Exchange_name,"item.insert",null,(message+"item.insert").getBytes());
channel.basicPublish(Exchange_name,"item.update",null,(message+"item.update").getBytes());
channel.basicPublish(Exchange_name,"item.insert.888",null,(message+"item.insert.888").getBytes());
//关闭资源
channel.close();
connection.close();
}
}
消费者1代码:
package com.zzy.topic;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
public class Consumer1 {
public static void main(String[] args) throws Exception {
//创建连接
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Producer.Exchange_name,BuiltinExchangeType.TOPIC);
// 声明(创建)队列
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列
* 参数3:是否独占本次连接
* 参数4:是否在不使用的时候自动删除队列
* 参数5:队列其它参数
*/
channel.queueDeclare(Producer.Quene_name1, true, false, false, null);
//队列绑定交换机
channel.queueBind(Producer.Quene_name1, Producer.Exchange_name, "item.#");
//创建消费者;并设置消息处理
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
/**
* consumerTag 消息者标签,在channel.basicConsume时候可以指定
* envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* properties 属性信息
* body 消息
*/
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由key
System.out.println("路由key为:" + envelope.getRoutingKey());
//交换机
System.out.println("交换机为:" + envelope.getExchange());
//消息id
System.out.println("消息id为:" + envelope.getDeliveryTag());
//收到的消息
System.out.println("消费者1-接收到的消息为:" + new String(body, "utf-8"));
}
};
//监听消息
/**
* 参数1:队列名称
* 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 参数3:消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name1, true, consumer);
}
}
消费者2代码:
package com.zzy.topic;
import com.rabbitmq.client.*;
import com.zzy.util.ConnectionUtil;
import java.io.IOException;
public class Consumer2 {
public static void main(String[] args) throws Exception {
//创建连接
Connection connection = ConnectionUtil.getConnection();
//创建频道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare(Producer.Exchange_name,BuiltinExchangeType.TOPIC);
// 声明(创建)队列
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列
* 参数3:是否独占本次连接
* 参数4:是否在不使用的时候自动删除队列
* 参数5:队列其它参数
*/
channel.queueDeclare(Producer.Quene_name2, true, false, false, null);
//队列绑定交换机
channel.queueBind(Producer.Quene_name2, Producer.Exchange_name, "item.insert.*");
//创建消费者;并设置消息处理
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
/**
* consumerTag 消息者标签,在channel.basicConsume时候可以指定
* envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志
(收到消息失败后是否需要重新发送)
* properties 属性信息
* body 消息
*/
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//路由key
System.out.println("路由key为:" + envelope.getRoutingKey());
//交换机
System.out.println("交换机为:" + envelope.getExchange());
//消息id
System.out.println("消息id为:" + envelope.getDeliveryTag());
//收到的消息
System.out.println("消费者2-接收到的消息为:" + new String(body, "utf-8"));
}
};
//监听消息
/**
* 参数1:队列名称
* 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复会删除消息,设置为false则需要手动确认
* 参数3:消息接收到后回调
*/
channel.basicConsume(Producer.Quene_name2, true, consumer);
}
}
RabbitMq5种模式总结
1、简单模式: 一个生产者、一个消费者,不需要设置交换机(使用默认的交换机)
2、工作队列模式( Work Queue): 一个生产者、多个消费者(竞争关系),不需要设置交换机(使用默认的交换机)
3、发布订阅模式 (Publish/subscribe): 需要设置类型为fanout的交换机,并且交换机和队列进行绑定,当发送消息到交换机后,交换机会将消息发送到绑定的队列
4、路由模式(Routing): 需要设置类型为direct的交换机,交换机和队列进行绑定,并且指定routing key,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列
5、通配符模式 (Topic): 需要设置类型为topic的交换机,交换机和队列进行绑定,并且指定通配符方式的routing key,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列
Spring Boot整合Rabbitmq
1、创建生产者工程
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<groupId>com.zzy</groupId>
<artifactId>rabbitmq-producer</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
启动引导类:
package com.zzy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
}
配置文件:
spring:
rabbitmq:
host: localhost
port: 5672
virtual-host: /
username: guest
password: guest
配置类:
package com.zzy.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitmqConfig {
//交换机名称
public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange";
//队列名称
public static final String ITEM_QUEUE = "item_queue";
//声明交换机
@Bean("topicExchange")
public Exchange getTopicExchange(){
return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
}
//声明队列
@Bean("topicQueue")
public Queue getQueue(){
return QueueBuilder.durable(ITEM_QUEUE).build();
}
//队列与交换机绑定
@Bean
public Binding getBinding(@Qualifier("topicExchange") Exchange exchange,@Qualifier("topicQueue") Queue queue){
return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs();
}
}
测试类:
package com.zzy.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class RabbitmqTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void test1(){
rabbitTemplate.convertAndSend(RabbitmqConfig.ITEM_TOPIC_EXCHANGE,"item.insert","message:insert");
rabbitTemplate.convertAndSend(RabbitmqConfig.ITEM_TOPIC_EXCHANGE,"item.update","message:update");
rabbitTemplate.convertAndSend(RabbitmqConfig.ITEM_TOPIC_EXCHANGE,"item.delete.888","message:delete.888");
}
}
2、消费者工程
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<groupId>com.zzy</groupId>
<artifactId>rabbitmq-consumer</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
启动引导类:
package com.zzy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
配置文件:
spring:
rabbitmq:
host: localhost
port: 5672
virtual-host: /
username: guest
password: guest
监听类:
package com.zzy.listener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbitmqListener {
/**
* 监听topicQueue队列
* @param message 接收到的数据
*/
@RabbitListener(queues = {"item_queue"})
public void Listener1(String message){
System.out.println(message);
}
}