springboot配置redis发布订阅 (pub/sub)

本文详细介绍了如何在Spring Boot应用中使用Jackson2JsonRedisSerializer进行Redis的数据序列化,包括配置RedisTemplate、发布消息、消息监听以及序列化设置。展示了如何在发布和接收消息时确保一致性,适合Redis开发者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、redis使用Jackson2JsonRedisSerializer 序列化

redis配置类

    @Bean(name = "redisTemplate")
    @SuppressWarnings({"unchecked", "rawtypes"})
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //使用 Jackson 序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        // value 值的序列化采用 jackson2JsonRedisSerializer
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        // key 的序列化采用 StringRedisSerializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

二、发布消息

redis操作工具类

    /**
     * 发布消息
     * @param message
     */
    public void publish(Object message){
        redisTemplate.convertAndSend("channel", message);
    }

三、redis消息监听

消息监听配置

@Configuration
public class RedisListenerConfig {

    @Autowired
    private MessageDelegate defaultMessageDelegate;

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory,
                                                   MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        container.setTaskExecutor(executor());

        //序列化对象(特别注意:发布的时候需要设置序列化;订阅方也需要设置序列化)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 监听适配器设置序列化
        messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);

        Map<MessageListenerAdapter, Collection<? extends Topic>> map = new HashMap<>();
        List<ChannelTopic> channelTopics = new ArrayList<>();
        ChannelTopic channelTopic = new ChannelTopic("channel");
        channelTopics.add(channelTopic);
        map.put(messageListenerAdapter, channelTopics);
        container.setMessageListeners(map);

        return container;
    }

    @Bean
    public TaskExecutor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setQueueCapacity(100);
        executor.initialize();
        return executor;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        // handleMessage 参数消息来的时候要调用的方法 默认是 handleMessage
        return new MessageListenerAdapter(defaultMessageDelegate, "handleMessage");
    }
}

四、消息来时调用的server方法

public interface MessageDelegate {
    void handleMessage(Object message);
}

在接口实现类的 handleMessage 方法获取到消息。

Spring Boot项目中整合Redis实现发布订阅功能,你需要使用`lettuce`或`spring-data-redis`库来操作Redis,并利用其内置的pub/sub功能。这里是一个简单的例子,首先确保你已经在pom.xml文件中添加了相应的依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-redis</artifactId> </dependency> </dependencies> ``` 然后创建一个RedisTemplate配置类,设置连接池: ```java import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.listener.ChannelTopic; import org.springframework.data.redis.listener.PubSubMessage; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { // 这里填写你的Redis连接配置,如 host、port 等 return new LettuceConnectionFactory("localhost", 6379); } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); // 如果需要序列化/反序列化数据,可以设置序列化策略 // template.setKeySerializer(new StringRedisSerializer()); // template.setValueSerializer(new GenericToStringSerializer<>(Object.class)); return template; } @Bean public RedisMessageListenerContainer messageListenerContainer(RedisTemplate<String, Object> template) { MessageListenerAdapter adapter = new MessageListenerAdapter( (PubSubMessage<String, String> message) -> handleSubscribeMessage(message), "subscribeChannel"); RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(template.getConnectionFactory()); container.addMessageListener(adapter, new ChannelTopic<>("publishChannel")); return container; } private void handleSubscribeMessage(PubSubMessage<String, String> message) { System.out.println("Received message on subscribe channel: " + message.getMessage()); // 这里处理接收到的消息,例如存储到其他地方或转发给其他服务 } } ``` 最后,在`handleSubscribeMessage`方法中,你可以编写处理接收消息的逻辑。当有新的消息发布到`"publishChannel"`时,所有订阅该频道的客户端都会收到通知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值