此文章介绍Springboot下整合RabbitMQ,分为生产者和消费者,工具使用idea
SpringBoot工程创建
使用idea创建新项目,选择springboot项目,在环境处添加Spring for RabbitMQ(Messaging内)
创建两个springboot项目,分别为producer生产者和consumer消费者
查看maven的依赖pom.xml对应坐标,producer生产者和consumer消费者都为以下坐标
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
修改配置文件application.yml
找到application.yml,或者修改配置文件为application.yml,producer生产者和consumer消费者都通用
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
virtual-host: /
producer生产者编写
编写配置类
package xyz.zhazong710.rabbitmqtest.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
//1.Exchange 交换机
@Bean("bootExchange")
public Exchange bootExchange() {
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2.Queue 队列
@Bean("bootQueue")
public Queue bootQueue() {
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3.Binding 队列和交换机绑定关系
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
编写生产者测试类
package xyz.zhazong710.rabbitmqtest.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import xyz.zhazong710.rabbitmqtest.config.RabbitMQConfig;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
//1.注入RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend() {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.zhazong", "zhazong springboot mq hello!");
}
}
consumer消费者编写
编写监听类
package xyz.zhazong710.rabbitmqtest.rabbitmqtestconsumer.config;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbitMQListener {
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message) {
System.out.println(new String(message.getBody()));
}
}
启动
启动生产者,在http://localhost:15672内查看队列和交换机,队列是否发出信息
启动消费者,查看消息是否被消费