Redis之PUB/SUB(發佈/訂閱)模式詳解

#Redis之PUB/SUB模式java

redis提供發佈/訂閱的功能

redis和rabbitMQ發佈訂閱功能的區別:web

  1. redis發佈訂閱是廣播模式的,redis發佈一條message,全部消費者均可以進行消費,而rabbitMQ隊列方式的,發佈一條message能夠通知全部訂閱者,可是這能有一個訂閱者消費message。
  2. redis消息不會緩存,當redis發佈消息以後沒有消費者消費也會消失,而rabbitMQ發佈消息以後不被消費就會一直存在。
  3. redis消息能夠是持久化的(取決於redis持久化方式和用戶邏輯),rabbitMQ消息消費以後就會消失。
  4. redis能夠設置發佈消息的key和action(稍後介紹)。
  5. 在分佈式環境下,redis能夠爲全部動態建立的實例節點發布消息。

redis發佈/訂閱應用場景:redis

  1. 分佈式環境下的配置中心配置改變,通知全部實例節點刷新配置。
  2. 多數據庫環境下數據的改變,通知全部數據庫同步數據。
  3. 第三方對接一對多場景,一次性廣播通知全部第三方服務。
  4. ……

java功能實現

  1. redis配置開啓發布/訂閱功能:

redis發佈/訂閱配置notify-keyspace-events的詳細配置見redis的配置文件裏面,spring

  1. 建立springboot web項目,並添加RedisMsgPubSubListener監聽器:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisMsgPubSubListener implements MessageListener {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        System.out.println("監聽到redis中YCYC數據變化:"+redisTemplate.opsForHash().values("YCYC"));
    }
}
  1. 添加redis配置,裝在監聽器:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.web.base.interceptor.RedisMsgPubSubListener;
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.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
//        container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@*:hset"));
        container.addMessageListener(listenerAdapter, new PatternTopic("__keyspace@*:YCYC"));

        return container;
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(RedisMsgPubSubListener receiver) {
        return new MessageListenerAdapter(receiver);
    }
}
  1. 添加測試Controller:
import com.yc.web.base.annotations.NoRepeatSubmit;
import com.yc.web.base.config.ResultInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(description = "redis")
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(response = ResultInfo.class, value = "setRedis", notes = "setRedis")
    @GetMapping(value = "/setRedis")
    @NoRepeatSubmit
    public ResultInfo setRedis() throws Exception {
//        redisTemplate.opsForValue().set("YCYC", "YC_chat");
        redisTemplate.opsForHash().put("YCYC", "YC1", System.currentTimeMillis());
        redisTemplate.opsForHash().put("YCYC", "YC2", System.currentTimeMillis());
//        redisTemplate.convertAndSend("YCYC","YC_chat");
        System.out.println("添加成功");
        return ResultInfo.Success();
    }

}
  1. 啓動項目測試,在Controller裏向redis裏設置hash格式數據,在RedisMsgPubSubListener就會監聽到redis中的數據變化:
添加成功
監聽到redis中YCYC數據變化:[1571367514510, 1571367514524]
監聽到redis中YCYC數據變化:[1571367514510, 1571367514524]
相關文章
相關標籤/搜索