You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在异步JmsOutboundGateway上实现高效线程重试

问题:基于JmsOutboundGateway的异步MQ请求重试优化

我使用JmsOutboundGateway进行MQ连接,输入通道为ExecutorChannel,当前ServiceActivator未配置输出通道,网关接口方法返回CompletableFuture对象。

现有实现代码

网关接口

@MessagingGateway
public interface SimpleGateway {

    @Gateway(requestChannel = "mqRequestChannel")
    CompletableFuture sendAndReceiveMqMessage(String message);
}

配置类与调用示例

@Bean
public MessageChannel mqRequestChannel(AsyncTaskExecutor taskExecutor) {
    return new ExecutorChannel(taskExecutor);
}

@ServiceActivator(inputChannel = "mqRequestChannel")
@Bean
public JmsOutboundGateway jmsOutboundGateway(... ) {
    JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setConnectionFactory(mqConnectionFactory);
    gateway.setRequestDestinationName(requestDestination);
    gateway.setReplyDestinationName(responseDestination);
    gateway.setAsync(true);
    // 其他配置省略
    return gateway;
}

@Autowired
private SimpleGateway simpleGateway;

// 调用示例
CompletableFuture<String> mqResponse = simpleGateway.sendAndReceiveMqMessage("sdsadas");

尝试过的递归重试方案(非最优)

我曾用递归实现重试逻辑,但该方案并非最优,相关代码如下:

private void callGateway(int retry, int requestNum){

    String dummyOfs = "dsfsdf";

    CompletableFuture<String> response = simpleGateway.sendAndReceiveMqMessage(dummyOfs);

    response.exceptionally(throwable -> { 
        LOG.info("error occured");
        LOG.info("[Error section CURRENT THREAD in gateway class call ]: {} , requestNum = {}, retry = {}", Thread.currentThread(), requestNum, retry );
        if(MAX_RETRY > retry){
            Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
            callGateway(retry + 1, requestNum);
        }
        return null;
    });

    response.thenAccept((String someString) -> {
        LOG.info("[success ]: {} , returned value: {}", Thread.currentThread(), someString);
    });
}

核心需求

  • 支持配置重试次数
  • 支持配置退避时间
  • 请求超时时,终止后续重试或不再触发新的重试

内容的提问来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:43:15