SpringBoot 整合 RabbitMQ 實踐

推薦閱讀:阿里P8架構師談:工作1-5年的Java工程師,怎樣提高核心競爭力

                  阿里架構師直言:“沒有實戰都是紙上談兵”!Redis實戰PDF分享

                  奮發圖強半年多,終於四面阿里如願拿到心儀offer定級P7

1.在linux環境使用docker安裝RabbitMQ


 
//拉取鏡像 docker pull rabbitmq:management //啓動鏡像 docker run -di --name myrabbit -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin -p 15672:15672 -p5672:5672 -p 25672:25672 -p 61613:61613 -p 1883:1883 rabbitmq:management

安裝成功後登陸控制檯

 

2.生產者

pom.xml中引入RabbitMQ依賴


 
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp --> <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-amqp</artifactId>   <version>1.3.5.RELEASE</version> </dependency>

配置RabbitMQ服務端連接,和交換機名稱

application.yml


 
spring:   rabbitmq:     port: 5672     username: admin     password: admin     host: 192.168.200.128     virtual-host: / order:   fanout:     exchange: order.fanout.exchange

生產者向MQ發送消息

Producer.java


 
package com.cott.gmail.bootuserserviceprovider.mq; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Date; import java.util.UUID; @Component public class Producer {     @Autowired     private RabbitTemplate rabbitTemplate;     @Value("${order.fanout.exchange}")     private String exchangeName;     public void sendMsg() {         String orderId = UUID.randomUUID().toString();         String message = "你的訂單信息是:" + orderId + ",日期是:" + new Date();         rabbitTemplate.convertAndSend(exchangeName, message);     } }

在用戶接口的實現類中,調用生產者的方法

UserServiceImpl.java


 
package com.cott.gmail.bootuserserviceprovider.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.cott.gmail.bean.UserAddress; import com.cott.gmail.bootuserserviceprovider.mq.Producer; import com.cott.gmail.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Service @Component public class UserServiceImpl implements UserService {     @Autowired     Producer producer;     @Override     public List<UserAddress> getAddress(String uesrId) {         producer.sendMsg();         UserAddress userAddress1 = new UserAddress();         userAddress1.setId(1);         userAddress1.setUserAddress("1");         userAddress1.setUserId("1");         UserAddress userAddress2 = new UserAddress();         userAddress2.setId(2);         userAddress2.setUserAddress("2");         userAddress2.setUserId("2");         return Arrays.asList(userAddress1, userAddress2);     } }

3.消費者

pom.xml中引入RabbitMQ依賴


 
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-amqp --> <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-amqp</artifactId>   <version>1.3.5.RELEASE</version> </dependency>

配置RabbitMQ服務端信息,和交換機以及隊列名稱

application.yml


 
spring:   rabbitmq:     port: 5672     username: admin     password: admin     host: 192.168.200.128     virtual-host: / order:   fanout:     exchange: order.fanout.exchange     queue: order.fanout.queue

@RabbitListener註解,綁定隊列,交換機,以及選擇交換模式FANOUT

  • @RabbitListener 可以標註在類上面,需配合 @RabbitHandler 註解一起使用
  • @RabbitListener 標註在類上面表示當有收到消息的時候,就交給 @RabbitHandler 的方法處理,具體使用哪個方法處理,根據 MessageConverter 轉換後的參數類型

Consumer.java(消費者)


 
package com.cott.gmail.bootorderserviceconsumer.service.impl; import org.springframework.amqp.core.ExchangeTypes; import org.springframework.amqp.rabbit.annotation.*; import org.springframework.stereotype.Component; @Component @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "${order.fanout.queue}", autoDelete = "true"), exchange = @Exchange(value = "${order.fanout.exchange}", type = ExchangeTypes.FANOUT))) public class Consumer {     @RabbitHandler     public void processMessage(String msg) {         System.out.format("Receiving Message: -----[%s]----- n.", msg);     } }

消費者中有調用生產者getAddress()的方法,生產者向MQ中發送一條消息,同時消費者監聽MQ,消費消息。

OrderServiceImpl.java


 
package com.cott.gmail.bootorderserviceconsumer.service.impl; import com.alibaba.dubbo.config.annotation.Reference; import com.cott.gmail.bean.UserAddress; import com.cott.gmail.service.OrderService; import com.cott.gmail.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class OrderServiceImpl implements OrderService {     @Reference     UserService userService;     @Override     public List<UserAddress> initOrder(String id) {         System.out.println("id= " + id);         List<UserAddress> list = userService.getAddress("1");         for (UserAddress user : list         ) {             System.out.println(user.getUserAddress());         }         return list;     } }

4.驗證

先後啓動生產者和消費者,在瀏覽器發起請求

 

消費者控制檯輸出

 

同時在RabbitMQ控制檯查看監控日誌

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章