导入依赖jar包
<!-- redis 配置信息--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
实现消息监听接口 MessageListener\重写 onMessage方法
/** * @author haizhuangbu * @date 2024/3/31 11:30 * @mark UserInfoRegisterTopicListen */ @Component @Slf4j public class UserInfoRegisterTopicListen implements MessageListener { @Autowired private RedisTemplate<String, String> redisTemplate; @Override public void onMessage(Message message, byte[] bytes) { log.info("接收到redis消息队列消息 : {}", message.toString()); } }
绑定 topic 与 监听器
@Configuration public class RedisTopicQueueConfig { @Autowired private UserInfoRegisterTopicListen userInfoRegisterTopicListen; /** * @param connectionFactory 连接工厂 * @return redis 监听容器 */ @Bean public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); redisMessageListenerContainer.setConnectionFactory(connectionFactory); // 连接工厂 redisMessageListenerContainer // 配置适配器与对应消息队列信息 .addMessageListener(new MessageListenerAdapter(userInfoRegisterTopicListen, MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD), new ChannelTopic(RedisTopicQueueEnum.USER_REGISTER.getTopic())); return redisMessageListenerContainer; } }
测试
代码测试
redisTemplate.convertAndSend("userRegister", String.format("用户 %s 注册失败", userDto.getUsername()));
消息消费成功