springboot 整合Redis订阅发布实现消息通知

最近做一个项目修改,B模块包含了A模块,但现在要在A模块里调用B模块里面定义的类实现修改,为了避免模块间的循环引用,决定转而使用Redis的发布订阅通知功能。

修改参考了(7条消息) springboot 整合使用redis发布订阅功能_springboot redis发布订阅_逆风飞翔的小叔的博客-CSDN博客

①检查最外层POM有无Redis依赖,以及yaml文件的redis配置

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://IP:3306/warehouse?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: 666
    druid:
      max-active: 100
      initial-size: 10
      max-wait: 60000
      min-idle: 5
 
  redis:
    host: localhost
    port:  6379
    password: ''

  cache:
    type: redis

②检查Redis配置类里的redisTemplate配置(A模块内)

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

③A模块内自定义RedisSubConfig(和Redis配置类一个包下),往容器(RedisMessageListenerContainer)内添加消息监听器以及它监听的管道(channel)

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.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.connection.MessageListener;

@Configuration
public class RedisSubConfig {
 
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory, MessageListener listener) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        //订阅频道topic1 和 topic2 这个container 可以添加多个 messageListener
        container.addMessageListener(listener, new ChannelTopic("topic1"));
        //container.addMessageListener(listener, new ChannelTopic("topic2"));
        return container;
    }
 
}

④B模块内自定义消息监听器,重写里面的onMessage方法,并定义消息处理方法。

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;
 
@Component
public class RedisMessageListener implements MessageListener {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
 
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
        System.out.println(patternStr);
        System.out.println(channel+":"+msg);
        if("topic1".equals(channel)){
            handleMsg(msg);
        }
    }
}

⑤在A模块中原先需要使用B模块代码的地方发送消息

@RestController
public class BussinessController {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @GetMapping("/bussiness")
    public String business(String jsonString){
        //A模块主业务
        ...
        //发送消息到B模块处理
        redisTemplate.convertAndSend("topic1", jsonString);
        return "success";
    }
 
}

至此修改完成。

该功能与springboot使用了redis哪个database无关(应用A可以使用db0,应用B可以使用db1),可以在不同的应用间使用。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答这个问题。以下是一个简单的 Spring Boot 整合 Redis 实现发布订阅消息的例子: 1. 首先,在 pom.xml 文件添加 Redis 相关依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在 application.properties 文件配置 Redis 连接信息: ``` spring.redis.host=localhost spring.redis.port=6379 ``` 3. 创建一个 Redis 发布者: ``` @Component public class RedisPublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } } ``` 4. 创建一个 Redis 订阅者: ``` @Component public class RedisSubscriber { @Autowired private MessageListenerAdapter messageListenerAdapter; @PostConstruct public void init() { redisTemplate.execute((RedisConnection connection) -> { connection.subscribe(messageListenerAdapter, "channel"); return null; }); } @PreDestroy public void destroy() { redisTemplate.execute((RedisConnection connection) -> { connection.unsubscribe(messageListenerAdapter, "channel"); return null; }); } } ``` 5. 在需要发布消息的地方调用 RedisPublisher 的 publish 方法: ``` @Autowired private RedisPublisher redisPublisher; redisPublisher.publish("channel", "message"); ``` 6. 在需要订阅消息的地方实现 MessageListener 接口: ``` @Component public class MyMessageListener implements MessageListener { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String messageBody = new String(message.getBody()); System.out.println("Received message: " + messageBody + " from channel: " + channel); } } ``` 以上就是一个简单的 Spring Boot 整合 Redis 实现发布订阅消息的例子。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值