需求
共同POM文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- 添加 junit 环境的 jar 包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
生产者
YML配置文件:
#设置交换器的名称
mq.config.exchange: log.direct
#info 路由键
mq.config.queue.info.routing.key: log.info.routing.key
#error 路由键
mq.config.queue.error.routing.key: log.error.routing.key
Sender.java
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitAmqpTemplate;
//exchange 交换器名称
@Value("${mq.config.exchange}")
private String exchange;
//routingkey 路由键
@Value("${mq.config.queue.info.routing.key}")
private String routingkey;
/*
* 发送消息的方法
*/
public void send(String msg){
//向消息队列发送消息
//参数一:交换器名称。
//参数二:路由键
//参数三:消息
this.rabbitAmqpTemplate.convertAndSend(this.exchange, this.routingkey, msg);
}
}
测试代码
/**
* 消息队列测试类
* @author Administrator
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes=App.class)
public class QueueTest {
@Autowired
private Sender sender;
/*
* 测试消息队列
*/
@Test
public void test1(){
this.sender.send("Hello RabbitMQ");
}
}
消费者(交换器 通过 路由键 绑定 队列)
YML配置文件:
#设置交换器的名称
mq.config.exchange: log.direct
#info 队列名称
mq.config.queue.info: log.info
#info路由键
mq.config.queue.info.routing.key: log.info.routing.key
JAVA代码
/**
* 消息接收者
* @author Administrator
* @RabbitListener bindings:绑定队列
* @QueueBinding value:绑定队列的名称 exchange:配置交换器
* @Queue value:配置队列名称 autoDelete:是否是一个可删除的临时队列
* @Exchange value:为交换器起个名称 type:指定具体的交换器类型
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.info}",autoDelete="true"),
exchange=@Exchange(value="${mq.config.exchange}",type=ExchangeTypes.DIRECT),
key="${mq.config.queue.info.routing.key}"
)
)
public class InfoReceiver {
/**
* 接收消息的方法。采用消息队列监听机制
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("Info........receiver: "+msg);
}
}
测试流程
先运行消费者的App.java
再运行生产者的测试代码