1.生产端
1. 创建生产者SpringBoot工程
2. 引入start,依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3. 编写yml配置,基本信息配置
spring:
rabbitmq:
host:公网ip
port:5671
username:
password:
virtual-host:
4. 定义交换机,队列以及绑定关系的Config配置类
@Configuration
public class RabbitMqConfig {
//定义交换机的名字
public static final String EXCHANGE_NAME = "boot_topic_exchange";
//定义队列的名字
public static final String QUEUE_NAME = "boot_queue";
//1、声明交换机
@Bean("bootExchange") //bean声明,加入到容器中
public Exchange bootExchange(){
//topicExchange: 主题交换机 durable:是否持久化
//ExchangeBuilder工具类调用topicExchange的API方法创建主题交换机
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2、声明队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3、队列与交换机进行绑定
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
5. 注入RabbitTemplate,调用方法,完成消息发送
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
//注入 RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void send(){
rabbitTemplate.convertAndSend("boot_topic_exchange","boot.haha","boot mq...");
}
}
2.消费端
1. 创建消费者SpringBoot工程
2. 引入start,依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3. 编写yml配置,基本信息配置
spring:
rabbitmq:
host:公网ip
port:5671
username:
password:
virtual-host:
4. 定义监听类,使用@RabbitListener注解完成队列监听。
@Component //声明这是一个组件
public class RabbitMQListener {
//定义方法进行信息的监听 RabbitListener中的参数用于表示监听的是哪一个队列
//如果有消息过来,就会执行这个方法,自动会把消息封装到Message对象中,取走消息之后会在队列里删除掉消息
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message){
System.out.println("message:"+message.getBody());
}
}
3.启动流程
先点击生产端的@test方法发送信息到队列中去,然后直接运行消费端的
@SpringBootApplication启动方法