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));
                    
}
相关推荐
один but you28 分钟前
const和constexpr常量表达式
java·前端·javascript
码云数智-大飞30 分钟前
RAII 与智能指针深度拆解
java·前端·算法
云烟成雨TD39 分钟前
Agent Scope Java 2.x 系列【19】Harness:从零搭建 MySQL 文件系统
java·人工智能·agent
qq36219670541 分钟前
阿里裁员新消息(2026最新动态汇总)
java·开发语言·前端
a11177642 分钟前
“黑夜流星“个人引导页 网页html
java·前端·html
砚底藏山河1 小时前
沪深A股:如何获取基金持股数据
java·python·数据分析·maven
代码改善世界1 小时前
【C++进阶】C++11:列表初始化、右值引用与移动语义、完美转发全解析
java·开发语言·c++
caimouse1 小时前
Reactos 第 10 章 网络操作 — 10.3.1 NIC驱动
网络·windows
AIGS0011 小时前
JBoltAI V4.5企业智能体平台:技术架构拆解
java·人工智能·ai大模型应用
一勺菠萝丶1 小时前
Maven SNAPSHOT 父 POM 无法解析问题排查
java·maven