微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Resilience4j + Spring boot @Retry 不适用于异步方法

如何解决Resilience4j + Spring boot @Retry 不适用于异步方法

我有一个 @Async 方法,我试图在其中添加 @Retry,但在发生异常时永远不会执行回退方法。我也在尝试测试抛出异常的这种模拟,但由于它永远不会进入回退方法,因此永远不会成功。

这是我的代码

@Retry(name = "inserTaroperacionPendienteService",fallbackMethod = "fallbackInserTaroperacionPendiente")
@Override
@Async
public CompletableFuture<String> inserTaroperacionPendiente(final OperacionPendienteWeb operacionPendienteWeb)  throws InterruptedException,ExecutionException {
    StringBuilder debugMessage = new StringBuilder("[inserTaroperacionPendiente] Operacion pendiente a insertar en BB.DD.: ").append(operacionPendienteWeb);
    CompletableFuture<String> result = new CompletableFuture<>();
    httpentity<List<OperacionPendienteWeb>> entity = new httpentity<>();
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("url");
    try {
        rest.exchange(builder.toUriString(),HttpMethod.POST,entity,Void.class);
    } catch (HttpClientErrorException | HttpServerErrorException e) {
        result.completeExceptionally(e);
    } catch (Exception e) {
        result.completeExceptionally(e);
    }   

    result.complete("OK");
    return result;
}

public CompletableFuture<String> fallbackInserTaroperacionPendiente(Exception e) {
       System.out.println("HI");
       throw new InternalServerErrorDarwinException("Error al insertar la operacion pendiente.");
}

测试:

@Test(expected = InternalServerErrorDarwinException.class)
public void procesarOperacionPendienteKO1() throws InterruptedException,ExecutionException,ParseException {
    when(rest.exchange(Mockito.anyString(),Mockito.any(HttpMethod.class),Mockito.any(httpentity.class),Mockito.eq(Void.class)))
    .thenThrow(new NullPointerException());

    this.operacionesPendientesService.inserTaroperacionPendiente(obtenerOperacionPendienteWeb()).get(); 

    verify(rest,timeout(100).times(1)).exchange(Mockito.anyString(),Mockito.eq(Void.class));

}

我错过了什么吗?

谢谢!

解决方法

您的代码如下所示:

try {
    rest.exchange(builder.toUriString(),HttpMethod.POST,entity,Void.class);
} catch (HttpClientErrorException | HttpServerErrorException e) {
    result.completeExceptionally(e);
} catch (Exception e) {
    result.completeExceptionally(e);
}   

result.complete("OK");

所以在最后一行你总是将结果设置为完成!

改为:

try {
    rest.exchange(builder.toUriString(),Void.class);
    result.complete("OK");
} catch (HttpClientErrorException | HttpServerErrorException e) {
    result.completeExceptionally(e);
} catch (Exception e) {
    result.completeExceptionally(e);
}   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。