欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

spingboot实现redis的发布订阅

发布时间:2023/12/31 编程问答 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 spingboot实现redis的发布订阅 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

配置订阅频道

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.listener.adapter.MessageListenerAdapter;/**订阅配置 topic1,topic2是频道,可以多个*/ @Configuration public class MyRedisMessageListenerContainer {@BeanMessageListenerAdapter messageListener() {return new MessageListenerAdapter(new MySubcribe());}@BeanRedisMessageListenerContainer redisContainer(RedisConnectionFactory factory) {final RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(factory);container.addMessageListener(messageListener(), new ChannelTopic("topic1"));container.addMessageListener(messageListener(), new ChannelTopic("topic2"));return container;} }

配置订阅者频道

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.StringRedisTemplate; import org.springframework.stereotype.Service;@Service public class MySubcribe implements MessageListener {@Autowiredprivate StringRedisTemplate redisTemplate;@Overridepublic void onMessage(Message message, byte[] pattern) {System.out.println("接收数据:"+message.toString());System.out.println("订阅频道:"+new String(message.getChannel()));} }

配置发布者:

//写入redis 队列redisTemplate.convertAndSend("topic1",insertSql);

总结

以上是生活随笔为你收集整理的spingboot实现redis的发布订阅的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。