1、監聽
1.1、監聽隊列
如訂單系統和庫存系統
訂單系統下訂單之后將消息存放在消息隊列中
庫存系統需要時刻進行監聽消息隊列的內容,有新的訂單就需要進行庫存相關的操作
此時模擬監聽消息隊列中的Book信息
編寫監聽類:
@RabbitListener監聽相關的消息隊列(這里只是做測試,所以方法里的參數直接寫的是Book類型,消息接收后,直接把消息的內容轉為了Book類型)
@Service public class BookService { //queues:監聽哪些隊列 @RabbitListener(queues = {"atguigu.news"}) public void receive(Book book){ System.out.println("atguigu.news隊列收到消息"+book); } }
在配置類中開啟基於注解的RabbitMQ模式
@EnableRabbit //開啟基於注解的RabbitMQ模式 @SpringBootApplication public class Springboot02AmqpApplication { public static void main(String[] args) { SpringApplication.run(Springboot02AmqpApplication.class, args); } }
開啟服務之后只要atguigu.news隊列中有消息,receive方法就會執行
測試:
1、開啟服務
2、在測試方法中給atguigu.news隊列發送消息
3、運行測試方法,發送消息
4、在主程序控制台中可以看到receive方法執行了
1.2、監聽方法中獲取消息頭、消息體相關的參數(直接把消息封裝成Message對象,注意別導錯包)
//import org.springframework.amqp.core.Message; //監聽atguigu消息隊列,獲取消息頭和消息體相關參數 @RabbitListener(queues = "atguigu") public void receive02(Message message){ System.out.println(message.getBody()); System.out.println(message.getMessageProperties()); }
消息如下:
監聽后的打印信息如下:
2、AmqpAdmin創建或刪除exchange、queue、binding
假設有些信道活着隊列不存在的情況
可以使用
AmqpAdmin進行創建交換器,轉換規則、隊列(Queue、Exchange、Binding)
2.1創建exchange
交換器的類型如下
@Autowired AmqpAdmin amqpAdmin; /** * 測試通過amqpAdmin創建exchange */ @Test public void creatExchange(){ //這里以創建direct類型的exchange為例 amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange")); System.out.println("創建交換器完成"); }
創建成功
2.2創建queue
/** * 測試通過amqpAdmin創建queue */ @Test public void creatQueue(){ amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true)); System.out.println("創建隊列完成"); }
創建成功
2.3創建binding
/** * 測試通過amqpAdmin創建binding */ @Test public void creatBinding(){ /** *創建Binding的參數解釋: * 1、目的隊列名稱 * 2、綁定的類型 * 3、exchange的名稱 * 4、綁定的路由鍵 * 5、一個map,需要是傳必要的參數,不需要是寫null就行 */ amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.haha",null)); System.out.println("創建綁定規則完成"); }
綁定成功