【轉】redis 訊息佇列發布訂閱模式spring boot實現

來源:互聯網
上載者:User

標籤:資料庫   set   項目   nta   工程   list   就是   mes   讀取   

 最近做項目的時候寫到一個事件推送的情境。之前的實現方式是起job一直查詢資料庫,看看有沒有最新的訊息。這種方式非常的不優雅,反正我是不能忍,由於羨慕本身就依賴redis,剛好redis 也有訊息佇列的功能,就簡單的使用redis 來實現這個訊息推送。

之前參考網上的例子,發現全部來自一個地方,spring 官方的一個例子,某些打著“非官方例子”的頭號,還是一樣就複製了一下官方的例子,怕是自己都沒搞懂代碼,原封不動的貼上來了,這邊順便提一句國內多數的部落格都是相互“借鑒”,有些自己都沒理解就把別人的內容 ctrl c  ctrl v 過來了。這邊我不貼官方的代碼,點這裡傳送 官方的例子。順便提一句。CountDownLatch 對象其實跟這個內容是無關的,這點我要提一下,具體功能我不多說,官方例子 是為了讓程式發送到 redis 通道裡面的 訊息被程式讀取之後 才結束程式 而引入的類。

       不多說 直接上代碼

 

 

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/**redis 訊息處理器*/@Componentpublic class MessageReceiver { /**接收訊息的方法*/public void receiveMessage(String message){System.out.println(message);} }  @Configurationpublic class RedisConfig {@BeanRedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);//訂閱了一個叫chat 的通道container.addMessageListener(listenerAdapter, new PatternTopic("chat"));//這個container 可以添加多個 messageListenerreturn container;} @BeanMessageListenerAdapter listenerAdapter(MessageReceiver receiver) {//這個地方 是給messageListenerAdapter 傳入一個訊息接受的處理器,利用反射的方法調用“receiveMessage”//也有好幾個重載方法,這邊預設調用處理器的方法 叫handleMessage 可以自己到源碼裡面看return new MessageListenerAdapter(receiver, "receiveMessage");} /**redis 讀取內容的template 這邊跟本工程無關,可以不配置*/@BeanStringRedisTemplate template(RedisConnectionFactory connectionFactory) {return new StringRedisTemplate(connectionFactory);}}
 來自CODE的代碼片redisConfig.java

 

 

上面 我把兩個類寫在了一起,第一個類 messageReceiver 注釋上也有說明,裡面只有一個方法,就是接收到訊息之後 處理,這邊示範我就簡單的將他列印在控制台上。

第二個類就是一些配置,注釋上我想也應該能看明白。

ok 接下裡就是啟動程式 看看效果

 

    ok 我用命令 publish 向 chat 通道推送了 helloword (提一下 integer 1 代表的就是 當前訂閱的使用者)

 

    完美在我程式裡面也收到這個訊息,並且列印在控制台上。

 

【轉】redis 訊息佇列發布訂閱模式spring boot實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.