Redis实现发布订阅

前言

在微服务中,一个微服务如果产生消息需要通知到其它的多个微服务,这个时候选择使用Redis的发布订阅模型。

依赖的坐标

因为涉及到对Redis的操作,因此需要引入Redis的起步依赖。

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

创建监听器

package org.heimi.listener;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

/**
* @description 监听器
* @author Administrator
* @date 2024-05-12 18:55
*/
@Component
public class TopicListener implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // TODO 一些业务逻辑可以在这里写
        System.out.println(message);
    }
}

这个类的作用是用来监听向Redis中发送的通知,收到消息后的一些业务逻辑在onMessage方法中写。

Redis配置类

package org.heimi.config;

import lombok.extern.slf4j.Slf4j;
import org.heimi.listener.TopicListener;
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;

/**
* @description redis配置类
* @author Administrator
* @date 2024-05-12 18:46
*/
@Slf4j
@Configuration
public class RedisConfig {

    // 定义频道名称
    public static final String CHANNEL_NAME = "channel:test";

    /**
    * @description 创建消息监听器容器
    * @author Administrator
    * @date 2024-05-12 19:16
    */
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            MessageListenerAdapter listenerAdapter
    ) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 设置订阅频道
        container.addMessageListener(listenerAdapter, new PatternTopic(CHANNEL_NAME));
        return container;
    }

    /**
    * @description 创建消息监听器适配器
    * @author Administrator
    * @date 2024-05-12 19:17
    */
    @Bean
    public MessageListenerAdapter messageListenerAdapter(TopicListener topicListener) {
        log.info("注册消息监听器适配器");
        return new MessageListenerAdapter(topicListener);
    }
}

在使用发布订阅的时候需要指定渠道,因为消息只能在相同的渠道中发送和接收。

其中渠道的名字可以根据自己的需求该,这里只是为了做测试

上述代码中消息监听适配器的作用是指定我们刚才所创建的监听器。

向当前渠道中发布信息

@Test
void contextLoads() {
    stringRedisTemplate.convertAndSend("channel:test", "hello");
}

这个在消息的监听者中就可以检测到发布的信息了。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值