SpringBoot進階教程(五十七)整合Redis 發布訂閱


SUBSCRIBE, UNSUBSCRIBE 和 PUBLISH 實現了 發布/訂閱消息范例,發送者 (publishers) 不用編程就可以向特定的接受者發送消息 (subscribers). Rather, 發布的消息進入通道,不需要知道有沒有訂閱者. 訂閱者發表感興趣的一個或多個通道,並且只接受他們感興趣的消息,不管發布者是不是存在. 發布者和訂閱者的解耦可以允許更大的伸縮性和更多動態的網絡拓撲。

關於發布訂閱(消息隊列)之前也過一篇《SpringBoot進階教程(二十二)集成RabbitMQ---MQ實戰演練》。感興趣的可以看看。今天說的發布訂閱,是基於Redis的。

v准備工作

學習本章節之前,建議依次閱讀以下文章,更好的串聯全文內容,如已掌握以下列出知識點,請跳過:

v命令行操作發布訂閱

下面實例中,圖中左側窗口視為客戶端1,右側窗口視為客戶端2.

1.1 客戶端1中訂閱頻道chatDemo

subscribe chatDemo

SpringBoot進階教程(二十九)整合Redis 發布訂閱

1.2 客戶端2向頻道chatDemo中發送兩次消息,客戶端1中會實時接收這兩次消息。

publish chatDemo "Hello World."

publish chatDemo "Hello Demo."

SpringBoot進階教程(二十九)整合Redis 發布訂閱

1.3 在客戶端1中退訂頻道,或者Ctrl+C退出redis連接模式。

unsubscribe chatDemo

SpringBoot進階教程(二十九)整合Redis 發布訂閱

以上例子中主要介紹了訂閱頻道、向指定的頻道發布消息、然后消息推送到訂閱者以及取消訂閱。

v項目中操作發布訂閱

2.1 消息監聽類

package com.demo.common;

import org.springframework.stereotype.Component;

/**
 * Created by toutou on 2019/2/23.
 */
@Component
public class RedisReceiver {
    public void receiveMessage(String message) {
        // TODO 這里是收到通道的消息之后執行的方法
        System.out.println(message);
    }
}

2.2 Redis消息訂閱配置類

package com.demo.Redis;

import com.demo.common.RedisReceiver;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * Created by toutou on 2019/1/20.
 */
@Configuration
@EnableCaching
public class RedisCacheConfig {
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 可以添加多個 messageListener,配置不同的交換機
        container.addMessageListener(listenerAdapter, new PatternTopic("channel:test"));

        return container;
    }

    /**
     * 消息監聽器適配器,綁定消息處理器,利用反射技術調用消息處理器的業務方法
     * @param receiver
     * @return
     */
    @Bean
    MessageListenerAdapter listenerAdapter(RedisReceiver receiver) {
        System.out.println("消息適配器1");
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
}

2.3 測試接口

package com.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created by toutou on 2019/1/20.
 */
@RestController
@Slf4j
public class RedisController {
    @Autowired
    StringRedisTemplate template;

    @RequestMapping(value = "/syncmessage")
    public String SyncMessage(){
        for(int i = 1; i <= 5; i++){
            try{
                // 為了模擬消息,sleep一下。
                Thread.sleep(2000);
            }catch(InterruptedException ex){}
            template.convertAndSend("channel:test", String.format("我是消息{%d}號: %tT", i, new Date()));
        }

        return "5";
    }
}

2.4 項目目錄結構

SpringBoot進階教程(二十九)整合Redis 發布訂閱

2.5 運行效果

SpringBoot進階教程(二十九)整合Redis 發布訂閱

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM