温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Redis中PUB/SUB模式是什么

发布时间:2021-11-15 11:02:22 来源:亿速云 阅读:330 作者:iii 栏目:大数据

这篇文章主要讲解了“Redis中PUB/SUB模式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Redis中PUB/SUB模式是什么”吧!

redis提供发布/订阅的功能

redis和rabbitMQ发布订阅功能的区别:

  1. redis发布订阅是广播模式的,redis发布一条message,所有消费者都可以进行消费,而rabbitMQ队列方式的,发布一条message可以通知所有订阅者,但是这能有一个订阅者消费message。

  2. redis消息不会缓存,当redis发布消息之后没有消费者消费也会消失,而rabbitMQ发布消息之后不被消费就会一直存在。

  3. redis消息可以是持久化的(取决于redis持久化方式和用户逻辑),rabbitMQ消息消费之后就会消失。

  4. redis可以设置发布消息的key和action(稍后介绍)。

  5. 在分布式环境下,redis可以为所有动态创建的实例节点发布消息。

redis发布/订阅应用场景:

  1. 分布式环境下的配置中心配置改变,通知所有实例节点刷新配置。

  2. 多数据库环境下数据的改变,通知所有数据库同步数据。

  3. 第三方对接一对多场景,一次性广播通知所有第三方服务。

  4. ……

java功能实现

  1. redis配置开启发布/订阅功能:

Redis中PUB/SUB模式是什么

redis发布/订阅配置notify-keyspace-events的详细配置见redis的配置文件里面,

Redis中PUB/SUB模式是什么

  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]

感谢各位的阅读,以上就是“Redis中PUB/SUB模式是什么”的内容了,经过本文的学习后,相信大家对Redis中PUB/SUB模式是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI