简单工作队类的实现配置步骤(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: 9005
spring:
application:
name: demo04
rabbitmq:
host: 120.55.58.250
port: 5672
password: guest
username: guest
- 创建配置类,声明队列
@Configuration
public class TopicQueueConfig {
public static String queueName01="topic.queue01";
public static String queueName02="topic.queue02";
public static String exchangeName="topic.exchange";
@Bean
public Queue topicQueue01(){
return new Queue(queueName01);
}
@Bean
public Queue topicQueue02(){
return new Queue(queueName02);
}
@Bean
public TopicExchange topicExchange(){
return new TopicExchange(exchangeName);
}
@Bean
//绑定交换机和队列
public Binding bindingQueue01(Queue topicQueue01, TopicExchange topicExchange){
return BindingBuilder.bind(topicQueue01).to(topicExchange).with("topic.A");
}
@Bean
//绑定交换机和队列
public Binding bindingQueue02(Queue topicQueue02,TopicExchange topicExchange){
return BindingBuilder.bind(topicQueue02).to(topicExchange).with("topic.#");
}
}
- 使用消息生产者发送消息
@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:9005/sendMessage02
http://localhost:9005/sendMessage01
结果展示
http://localhost:9005/sendMessage01
http://localhost:9005/sendMessage02