mqtt消费堆积

mqtt发送主题成功,但消费主题只有一个

代码实例:

java 复制代码
    @ServiceActivator(inputChannel = "caGetConfig")
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        try {
            String payload = (String) message.getPayload();
            String topic = (String) message.getHeaders().get(MQTTRECEIVEDTOPIC);
            log.info("接收到MQTT消息,主题: {}, 消息内容: {}", topic, payload);
            try {
                if (StringUtils.isEmpty(payload)) {
                    log.info("接收到空的MQTT消息,主题: {}", topic);
                    CompletableFuture.runAsync(() -> generateVideoService.getNeMessage());
                    return;
                }
                if (StringUtils.isBlank(topic)) {
                    log.info("接收到空的MQTT消息,主题: {}", topic);
                    CompletableFuture.runAsync(() -> generateVideoService.getNeMessage());
                }
                // 处理MQTT消息
                List<String> onlineStatusNewLis = JSON.parseArray(payload, String.class);
                if (CollectionUtils.isNotEmpty(onlineStatusNewLis)){
                    generateVideoService.getNeMessageByUrl(onlineStatusNewLis)
                }
            } catch (Exception e) {
                log.error("分发MQTT消息失败,主题: {}, 消息: {}", topic, payload, e);
            }
        } catch (Exception e) {
            log.error("处理MQTT消息失败,消息: {}", message, e);
        }
    }

问题分析:

1. MQTT 消费者是单线程的

@ServiceActivator(inputChannel = "caGetConfig") 基于 Spring Integration MQTT,其 inputChannel 默认是 PublishSubscribeChannel(同步调用),即消息的接收和处理在同一线程中串行执行。只有当 handleMessage() 方法返回后,才能处理下一条消息。

2. 使用 CompletableFuture.runAsync 异步调用

generateVideoService.getNeMessageByUrl(onlineStatusNewLis);方法执行完才能返回。如果 onlineStatusNewLis 列表较大,或者数据库查询较慢,这段时间内 MQTT 消费线程就会被阻塞。

如果该方法里面是一个 while(!Thread.currentThread().isInterrupted()) 的无限循环 ,这个循环会在 MQTT 消费线程上执行,永远无法返回,后续所有消息都将被彻底阻塞。

添加异步编排执行,解决阻塞

java 复制代码
// 处理MQTT消息
List<String> onlineStatusNewLis = JSON.parseArray(payload, String.class);
if (CollectionUtils.isNotEmpty(onlineStatusNewLis)){
  CompletableFuture.runAsync(() -> generateVideoService.getNeMessageByUrl(onlineStatusNewLis));
                    
}
相关推荐
悠仁さん5 分钟前
非类型模板参数的特化与偏特化
java·数据结构·算法
鬼手点金12 分钟前
上下文:Agent 的眼睛
java·前端·人工智能·git·深度学习
171320330计算机毕设编程29 分钟前
计算机毕业设计 基于Hadoop的新能源汽车发展前景分析 LW PPT
java·大数据·hadoop·python·算法·随机森林·线性回归
技术小结-李爽31 分钟前
【工具】怎么在终端中启动springboot项目?
java·spring boot·后端·maven
Shaoshing37 分钟前
消息发送
java·开发语言
DongQiShanRen1 小时前
六根硬件映射(下):物理闭环五步法,抽一条已实装的看
大数据·jvm·人工智能·算法·rust·哈希算法·集成学习
Code_Solitude1 小时前
c语言:指针(3)+冒泡排序
java·c语言·算法
乌暮1 小时前
从 `println` 到生产级日志:Spring Boot 日志体系完全指南
java·开发语言·jvm·spring boot·后端·学习·面试
脉动数据行情1 小时前
Java OkHttp 对接国际期货批量行情 SpringBoot 定时落库实践
java·spring boot·okhttp