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));
                    
}
相关推荐
phltxy5 小时前
C语言操作符详解
java·c语言·算法
步行cgn6 小时前
@Configuration 详解:Spring 配置类的核心注解
java·后端·spring
sunshine22 girl6 小时前
Java学习一 环境配置2 安装和基本使用Idea
java·学习·intellij-idea
嘿嘿-667 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
郝学胜-神的一滴8 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
策案案案8 小时前
YOLO: 将AI Agents嵌入到IntelliJ IDEA
java·大数据·人工智能·笔记·yolo·microsoft·intellij-idea
辰烨chenye10 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
寺中人10 小时前
MySQL 8.0 Windows 完整安装教程:环境配置、密码重置与常见报错排查
数据库·windows·mysql·环境搭建·mysql 安装
shehuiyuelaiyuehao10 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
小刘在重生~11 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python