Redis發佈訂閱簡例

Redis除了可以實現緩存功能以外,還可以用於不同服務之間消息的發佈、訂閱,可以實現消息提供方處理完成後,及時的將消息返回。例子比較簡單就寫在一起:

1、安裝redis並開啓:redis-server.exe redis.windows.conf

2、新建springboot項目,添加maven依賴

<!-- springmvc -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>

3、appliction.yml添加redis配置

server:
  port: 2019
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 1234
    timeout: 3000ms
    jedis:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

4、定義監聽器和監聽方法

package com.ccl.testst.redis_ps;


import com.alibaba.fastjson.JSONArray;

/**
 * 自定義監聽器和監聽方法
 */
public class Receiver {
    public void receiveMessage(String message){
        // 接收數據爲數組形式的字符串,轉換成JSONArray
        System.out.println("收到:"+ JSONArray.parseArray(message));
    }
}

5、訂閱配置,

package com.ccl.testst.redis_ps;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * 使用redis訂閱消息
 */
@Configuration
public class MessageListenerConfig {
    /**
     * 注入監聽器:綁定消息監聽者Receiver()和監聽方法receiveMessage
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(){
        return new MessageListenerAdapter(new Receiver(),"receiveMessage");
    }

    /**
     * 配置消息監聽容器
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory){
        // 容器
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        // 連接工廠
        container.setConnectionFactory(redisConnectionFactory);
        // 添加消息監聽器
        container.addMessageListener(listenerAdapter(),new PatternTopic("ccl_topic"));
        return container;
    }
}

6、發佈消息,此處和訂閱寫在一起,也可以實現異構服務之間的調用

package com.ccl.testst.redis_ps;

import com.alibaba.fastjson.JSON;
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.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private StringRedisTemplate template;

    @RequestMapping("/publish")
    public String publish(){
        List<String> result = new ArrayList<>();
        for(int i=0;i<10;i++){
            result.add("第"+i+"次發佈的消息!");
        }
        // 使用StringRedisTemplate講消息發佈到ccl_topic主題上,並轉換成字符串形式傳遞
        template.convertAndSend("ccl_topic", JSON.toJSONString(result));
        return "SUCCESS";
    }

}

7、瀏覽器訪問:http://localhost:2019/redis/publish即可實現消息訂閱。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章