1.創建了兩個項目 :
(1).spring_cloud_rabbitmq_send 消息發送者
(2).spring_cloud_rabbitmq_receive 消息接受者
2. 添加rabbitmq依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
3.編寫具體的消息發送者
(1)配置application.yml
spring: application: name: rabbitmq-send rabbitmq: host: localhost port: 5672 username: guest password: guest
#不分配端口,默認使用8080
(2)創建rabbitmq配置類,添加一個名為hello的隊列
1 /** 2 * @author liuboren 3 * @Title:Rabbit配置類 4 * @Description: 5 * @date 2018/6/27 14:57 6 */ 7 @Configuration 8 public class RabbitConfig { 9 public final static String QUEUE_NAME = "hello"; 10 11 @Bean 12 public Queue helloQueue(){ 13 return new Queue(QUEUE_NAME); 14 } 15 16 }
(3)編寫具體的發送組件
1 /** 2 * @author liuboren 3 * @Title:消息發送者 4 * @Description: 5 * @date 2018/6/27 14:40 6 */ 7 @Component 8 public class Sender { 9 10 //通過注入的這個類來傳遞消息 11 @Autowired 12 private AmqpTemplate rabbitTemplate; 13 14 public void send(){ 15 String context = "hello"+ new Date(); 16 System.out.println("Sender :"+ context); 17 18 //hello為創建的隊列名,context為發送的消息 19 this.rabbitTemplate.convertAndSend("hello",context); 20 } 21 22 }
(4)創建一個訪問接口,用以發送消息
/** * @author liuboren * @Title:發送消息的接口 * @Description: * @date 2018/6/27 15:36 */ @RestController public class SendController { @Resource private Sender sender; @GetMapping("send") public String send(){ sender.send(); return "消息已發送.."; } }
4. 編寫具體的消息接受者
(1)application.yml
spring:
application:
name: rabbitmq-receive
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
server:
port: 8081
(2)編寫消息接受者組件
1 /** 2 * @author liuboren 3 * @Title:消息接受者 4 * @Description: 5 * @date 2018/6/27 14:54 6 */ 7 @Component 8 //監聽hello隊列 9 @RabbitListener(queues = "hello") 10 public class Receive { 11 12 //處理接受到的消息 13 @RabbitHandler 14 public void process(String hello){ 15 System.out.println("Receiver:"+hello); 16 } 17 }
5. 測試
(1)啟動消息發送者,多次訪問http://localhost:8080/send
控制台輸出:
注意這時候我們還沒有啟動消息接受者,所有發送的消息都在消息隊列里面
可以訪問 http://localhost:15672/ 查看rabbitmq的管理頁面
我們可以看到消息隊列里面有21條消息
(2)我們啟動消息接受者應用
可以看到應用啟動好以后,接收到了消息
我們再次訪問http://localhost:15672
發現隊列此時已經沒有消息.
這樣一個簡單的RabbitMQ應用就完成了.
Github地址:https://github.com/liuboren0617/rabbit_demo