前言
在微服务中,一个微服务如果产生消息需要通知到其它的多个微服务,这个时候选择使用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");
}
这个在消息的监听者中就可以检测到发布的信息了。