在上一篇隨筆中咱們認識並安裝了RabbitMQ,接下來咱們來看下怎麼在Spring Boot 應用中整合RabbitMQ。html
先給出最終目錄結構:java
搭建步驟以下:spring
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sam</groupId> <artifactId>amqp</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <javaVersion>1.8</javaVersion> </properties> <dependencies> <!-- 引入amqp依賴,它能很好的支持RabbitMQ --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <!-- 引入test依賴,此次須要用到JUnit --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project>
spring.application.name=rabbitmq-hello
#config rabbitmq info
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
/** * 這裏沒什麼特殊的地方,就是普通的spring boot 配置 * */ @SpringBootApplication public class RabbitMQApp { public static void main(String[] args) { SpringApplication.run(RabbitMQApp.class, args); } }
@Component public class Sender { @Autowired AmqpTemplate rabbitmqTemplate; /** * 發送消息 */ public void send() { String content = "Sender says:" + "'hello, I'm sender'"; System.out.println(content); rabbitmqTemplate.convertAndSend("hello", content); } }
/** * 經過@RabbitListener對hello隊列進行監聽 * */ @Component @RabbitListener(queues="hello") public class Receiver { /** * 經過@RabbitHandler聲明的方法,對hello隊列中的消息進行處理 */ @RabbitHandler public void receiver(String str) { System.out.println("Receiver says:[" + str + "]"); } }
/** * rabbitmq配置類, * 爲了簡單,咱們這裏只配置了Queue * 至於exchanges、brokers等用的默認配置 * */ @Configuration public class RabbitConfig { @Bean public Queue helloQueue() { return new Queue("hello"); } }
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=RabbitMQApp.class) public class HelloTest { @Autowired private Sender sender; /** * 調用生產者進行消息發送 */ @Test public void hello() throws Exception{ sender.send(); } }
切換到amqp應用的控制檯,能看到打印:apache
在管理頁面中咱們能看到Connections和Channels中包含了當前鏈接的條目:併發
在整個生產和消費的過程當中,生產和消費是一個異步操做,這是分佈式系統中要使用消息代理的重要緣由。app