简单工作队类的实现配置步骤(5步)
- 引入AMQP的依赖
- 创建配置文件,链接消息队列(port name MQ账号密码)
- 创建配置类,声明队列
- 使用消息生产者发送消息
- 使用消息消费者接受消息
1 引入AMQP的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 创建配置文件,链接消息队列(port name MQ账号密码)
server:
port: 9004
spring:
application:
name: demo04
rabbitmq:
host: 120.55.58.250
port: 5672
password: guest
username: guest
- 创建配置类,声明队列
@Configuration
public class DirectQueueConfig {
public static String queueName01="direct.queue01";
public static String queueName02="direct.queue02";
public static String exchangeName="direct.exchange";
@Bean
public Queue directQueue01(){
return new Queue(queueName01);
}
@Bean
public Queue directQueue02(){
return new Queue(queueName02);
}
@Bean
public DirectExchange directExchange(){
return new DirectExchange(exchangeName);
}
@Bean
//绑定交换机和队列
public Binding bindingQueue01(Queue directQueue01, DirectExchange directExchange){
return BindingBuilder.bind(directQueue01).to(directExchange).with("routingkey.A");
}
@Bean
//绑定交换机和队列
public Binding bindingQueue02(Queue directQueue02,DirectExchange directExchange){
return BindingBuilder.bind(directQueue02).to(directExchange).with("routingkey.B");
}
}
- 使用消息生产者发送消息
@RestController
public class TestController {
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("/sendMessage01")
public void sendMessage01(){
for (int i=1;i<=5;i++){
rabbitTemplate.convertAndSend("direct.exchange","routingkey.A","路由模式routingA"+i);
}
}
@RequestMapping("/sendMessage02")
public void sendMessage02(){
for (int i=1;i<=5;i++){
rabbitTemplate.convertAndSend("direct.exchange","routingkey.B","路由模式routingB"+i);
}
}
}
- 使用消息消费者接受消息
@Component
public class ReceiveListener {
@RabbitListener(queues="direct.queue01")
public void ReceiveMessage01(String message){
System.out.println("ReceiveMessage01"+message);
}
@RabbitListener(queues="direct.queue02")
public void ReceiveMessage02(String message){
System.out.println("ReceiveMessage02"+message);
}
}
测试地址
http://localhost:9004/sendMessage01
http://localhost:9004/sendMessage02
结果展示
http://localhost:9004/sendMessage01
http://localhost:9004/sendMessage02
![在这里插入图片描述](https://img-blog.csdnimg.cn/73678c1564a54d5b944f07190c55c357.png#pic_center)