角色:
生产者(Producer)
消费者(Consumer)
1、创建两个子工程(module)
2、同时导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3、同时配置配置文件内容
spring:
rabbitmq:
host: 127.0.0.1 //ip 默认为主机
port: 5672 //端口 默认为5672
username: Cyrus //默认为guest
password: 123456 //默认为guest
virtual-host: /cyrus
4、编写生产者配置
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topics_exchange";
public static final String QUEUE_NAME = "boot_queue";
//1、交换机
@Bean("bootExchange")
public Exchange bootExchange() {
//采用topics通配符路由方法
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2、队列
@Bean("bootQueue")
public Queue bootQueue() {
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3、队列和交换机互相绑定的关系 Binding
/**
* 1、知道那个队列
* 2、知道那个交换机
* 3、routing key
*/
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
5、使用测试类发送消息到MQ
@SpringBootTest
public class TestDemo {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void test1() {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.Hello", "Hello World By MQ");
}
}
6、编写消费者监听器进行监听
@Component
public class RabbitMQListener {
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message) {
System.out.println(new String(message.getBody()));
}
}