赞
踩
步骤
消息监听
@Component public class RedisListener implements MessageListener { @Resource private RedisTemplate<String,Object> 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); System.out.println("---消息内容---: " + msg); } }
创建监听配置类
订阅多个频道使用通配符 *
package com.mucd.config; import com.mucd.service.RedisListener; 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; /** * @author mucd */ @Configuration public class RedisConfiguration { @Bean public RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisListener listener) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(factory); //订阅频道redis.news 和 redis.life 这个container 可以添加多个 messageListener container.addMessageListener(listener, patternTopic()); return container; } /** * 订阅多个topic * @return new PatternTopic */ @Bean public PatternTopic patternTopic(){ return new PatternTopic("redis.*"); } }
如果只订阅个别频道使用下面的方式
package com.mucd.config; import com.mucd.service.RedisListener; 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; /** * @author mucd */ @Configuration public class RedisConfiguration { @Bean public RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisListener listener) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(factory); //container可以添加多个订阅频道 container.addMessageListener(listener,new ChannelTopic("topic")); container.addMessageListener(listener,new ChannelTopic("topic02")); return container; } }
测试
@Resource
private RedisTemplate<String, Object> redisTemplate;
@RequestMapping("/send")
public void test01() {
redisTemplate.convertAndSend("redis.username", "redis发布的第一条消息");
redisTemplate.convertAndSend("redis.life", "redis发布的第一条消息");
log.info("执行完成!");
}
2022/07/21
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。