SpringCloud分布式微服务b2b2c电子商务(十二)在springboot中用redis实现消息队列
发表于:2025-12-04 作者:千家信息网编辑
千家信息网最后更新 2025年12月04日,准备阶段安装redis,可参考我的另一篇文章java 1.8maven 3.0idea环境依赖创建一个新的springboot工程,了解springcloud架构可以加求求:三五三六二四七二五九。在其
千家信息网最后更新 2025年12月04日SpringCloud分布式微服务b2b2c电子商务(十二)在springboot中用redis实现消息队列
准备阶段
安装redis,可参考我的另一篇文章
java 1.8
maven 3.0
idea
环境依赖
创建一个新的springboot工程,了解springcloud架构可以加求求:三五三六二四七二五九。在其pom文件,加入spring-boot-starter-data-redis依赖:
org.springframework.boot spring-boot-starter-data-redis
创建一个消息接收者
REcevier类,它是一个普通的类,需要注入到springboot中。
public class Receiver { private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class); private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { LOGGER.info("Received <" + message + ">"); latch.countDown(); }}注入消息接收者
@Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } @Bean StringRedisTemplate template(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); }注入消息监听容器
在spring data redis中,利用redis发送一条消息和接受一条消息,需要三样东西:
一个连接工厂
一个消息监听容器
Redis template
上述1、3步已经完成,所以只需注入消息监听容器即可:
@Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); }测试
在springboot入口的main方法:
public static void main(String[] args) throws Exception{ ApplicationContext ctx = SpringApplication.run(SpringbootRedisApplication.class, args); StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class); CountDownLatch latch = ctx.getBean(CountDownLatch.class); LOGGER.info("Sending message..."); template.convertAndSend("chat", "Hello from Redis!"); latch.await(); System.exit(0); }
消息
容器
监听
接收者
普通
东西
入口
只需
工厂
工程
文件
方法
架构
环境
篇文章
阶段
准备
参考
测试
中用
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
金山毒霸服务器升级
软件开发mini主机
睿民互联网科技是外包公司吗
如何修改域控服务器管理员密码
ALPHABET翻译软件开发
网络安全感量表
哪培训机构学软件开发比较好
云服务器管理运维试题答案
天下互联网科技有限公司
备份服务器怎么查看速度
mysql用命令显示数据库
杭州软件开发平台需要多少钱
软件角度数据库系统的核心
美国matweb数据库
中国计算机网络安全环境特点
数据库管理技术三个阶段
平行数据库
通过网页查看服务器数据
电脑远程登陆服务器怎么查
2005数据库怎么改名字
什么东西需要用到数据库
数据库技术主要的内容
哪培训机构学软件开发比较好
在数据库创建kc表
天下互联网科技有限公司
阳春颜楼网络技术有限公司
网络安全普通人怎么做
改公司服务器密码违法吗
大染坊小说软件开发
浦东新区安装网络技术哪家强