JMS&AMQP的簡介
RabbitMQ運行機制
direct:點對點 交換機根據路由鍵發送消息
fanout:交換機給每個隊列發送消息
topic:給指定規則的隊列發送消息 #匹配一個或多個單詞 *匹配一個單詞
Exchange(分發策略) --> 綁定Queue --> 綁定規則
點對點
廣播模式:
SpringBoot&AMQP 使用
1、在SpringBoot啓動類上面標註
@EnableRabbit //開啓基於註解的rabbitmq
2、監聽消息隊列
@RabbitListener(queues="zm.news") //監聽消息隊列
方法入參默認是一個RabbitMQ的Message類型
AMQP的新建操作
@Test
publicvoidcreateExchange(){
//新建交換器//名稱//是否持久化//是否自動刪除
admin.declareExchange(newDirectExchange("amqp.exchange",true,false));
System.out.println("amqp.exchange");
//新建隊列
Strings=admin.declareQueue(newQueue("admin.queue"));
System.out.println(s);
//綁定隊列到交換器上
admin.declareBinding(newBinding("admin.queue",Binding.DestinationType.QUEUE,"amqp.exchange","admin.qqq",null));
}
AMQP消息發送的操作
/**
*1、點對點
*/
@Test
publicvoidsend(){
//rabbitTemplate.send(交換機,路由鍵,消息體);
//消息體可以直接傳入對象將會自動序列化
//rabbitTemplate.convertAndSend(交換機,路由鍵,消息體);
HashMap<Object,Object>objectObjectHashMap=newHashMap<>();
objectObjectHashMap.put("name","zm");
objectObjectHashMap.put("list",Arrays.asList("1","2","3","4"));
Bookbook=newBook();
book.setId("1");
book.setName("書名1");
book.setPrice("12.3");
//對象被默認序列化
rabbitTemplate.convertAndSend("amqp.exchange","admin.qqq",book);
}
/*
*給exchange.fanout交換機下所有隊列發送消息
*/
@Test
publicvoidsendAll(){
Bookbook=newBook();
book.setId("1");
book.setName("書名1");
book.setPrice("12.3");
//對象被默認序列化
rabbitTemplate.convertAndSend("exchange.fanout","zm.news",book);
}
/*
*給exchange.Topic交換機下所有隊列根據規則發送消息
*/
@Test
publicvoidsendByTopic(){
Bookbook=newBook();
book.setId("1");
book.setName("書名1");
book.setPrice("12.3");
//對象被默認序列化
rabbitTemplate.convertAndSend("exchange.topic","xxx.news",book);
}