標籤:override 一起 java null text array web管理 hashmap 自訂
基於第一篇文章搭建好環境以後,我們這篇文章繼續介紹如何在springboot中使用RabbitMQ。
1)、單播:添加好pom檔案和自訂配置後,來看:
@Autowired RabbitTemplate rabbitTemplate; @Test public void contextLoads() { // 對象被預設JAVA序列化發送,參數:Exchange,routingKey,訊息 rabbitTemplate.convertAndSend("exchange.direct", "iceoooodin.news", "瓦爾克莉"); }
來看看我們發送的訊息是否成功了:
,成功擷取了~。
同樣,使用代碼來直接擷取:
@Test public void receive() { // 接受資料 Object o = rabbitTemplate.receiveAndConvert("iceoooodin.news"); System.out.println(o.getClass()); System.out.println(o); }
另外,我們除了str類型,還是發送map、對象等等,比如:
@Test public void contextLoads() { Map<String, Object> map = new HashMap<>(); map.put("msg", "第一個資料"); map.put("data", Arrays.asList("helloworld", 123, true)); // 對象被預設JAVA序列化發送 rabbitTemplate.convertAndSend("exchange.direct", "iceoooodin.news", map); }
@Test public void contextLoads() { // 對象被預設JAVA序列化發送 rabbitTemplate.convertAndSend("exchange.direct", "iceoooodin.news", new Book("金瓶M", "em..")); }
public class Book { private String bookName; private String author; @Override public String toString() { return "Book{" + "bookName=‘" + bookName + ‘\‘‘ + ", author=‘" + author + ‘\‘‘ + ‘}‘; } public Book(String bookName, String author) { this.bookName = bookName; this.author = author; } public Book() { } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; }}Book.java
2)、然後我們來看廣播,也就是發送一堆訊息是如何處理的:
@Test public void sendMst() { rabbitTemplate.convertAndSend("exchange.fanout", "", new Book("紅樓", "草 ")); }
如果發送的是廣播,可以發現,訊息會被分別發送到匹配的全部訊息佇列中:
3)、我們學會發送和接收了,再看看如何建立Exchange或者Queue吧,我們建立和綁定寫在了一起,根據需要自己拆:
@Autowired AmqpAdmin amqpAdmin; //這個amqpadmin是用來管理QP的,可以建立、刪除等操作; @Test public void creatExchange() { // 建立Exchange amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange")); System.out.println("建立exchange完成"); // 建立Queue amqpAdmin.declareQueue(new Queue("amqpadmin.queue", true));
System.out.println("建立Queue完成"); // 綁定 amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE, "amqpadmin.exchange", "amqp.haha", null)); }
結果就懶得寫了,大家自己實驗看一下就知道了,到web管理介面看看是否有正確添加和綁定~
SpringBoot日記——MQ訊息佇列整合(二)