最近做一个项目修改,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),可以在不同的应用间使用。