生产者
创建SpringBoot项目
配置pom.xml ,rabbitmq依赖
<!--RabbitMQ 启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
编写yml配置,基本信息配置
#配置rabbitmq
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: admin
password: admin
virtual-host: my_vhost
定义交换机,队列以及绑定关系的配置类
@Configuration
public class RabbitMqConfig {
/**
* 定义交换机和队列的名字
*/
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
/**
* 1、声明交换机
*
* @return
*/
@Bean("bootExchange")
public Exchange bootExchange() {
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
/**
* 2、声明队列
*
* @return
*/
@Bean("bootQueue")
public Queue bootQueue() {
return QueueBuilder.durable(QUEUE_NAME).build();
}
/**
* 3、队列与交换机进行绑定
*
* @param queue 需要绑定队列
* @param exchange 需要绑定的交换机
* @return
*/
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
注入RabbitTemplate,调用方法,完成消息发送
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
@Resource
private RabbitTemplate rabbitTemplate;
@Test
public void sendTest() {
rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, "boot.#", "boot.mq");
}
}
消费者
创建SpringBoot项目
配置pom.xml ,rabbitmq依赖
<!--RabbitMQ 启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
编写yml配置,基本信息配置
#配置rabbitmq
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: admin
password: admin
virtual-host: my_vhost
定义监听类,使用@RabbitListener注解完成队列监听。
@Configuration
public class RabbitMqListener {
/**
* 定义队列的监听方法,RabbitListener表示监听哪一个队列
*
* @param message
*/
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message) {
System.out.println("message:" + message);
}
}
总结
-
SpringBoot提供了快速整合RabbitMQ的方式
-
基本信息再yml中配置,队列交互机以及绑定关系在配置类中使用Bean的方式配置
-
生产端直接注入RabbitTemplate完成消息发送
-
消费端直接使用@RabbitListener完成消息接收