在故障安全中打开断路器时如何停止重试

时间:2019-07-03 20:19:43

标签: failover retry-logic retrypolicy

public CircuitBreaker<Connection> circuitBreaker(){
    return new CircuitBreaker<>() //Break circuit open
            .handle(ConnectionException.class) //on this exception
            .withFailureThreshold(3) //if failure happens for 3 consecutive times
            .withSuccessThreshold(2) // Close circuit if 3 trail executions succees
            .withDelay(Duration.ofSeconds(120)); //trail executions with delay of 30 seconds

}


public RetryPolicy<Connection> retryPolicy(){
    return new RetryPolicy<>()
            .onFailedAttempt(e -> log.warn("Connection attempt to cache failed"))
            .withMaxRetries(2) //retry 2 times
            .withDelay(Duration.ofSeconds(5)); //every 5 seconds

}

private <T> Connection getRepositoryAdapter(String query){

    return Failsafe.with(fallback,retryPolicy,circuitBreaker)
            .get(this::connect);
}

以上代码段仅在重试后才调用fallback方法,即使电路断开。

我们如何配置故障回复,以便在电路断开时,无需重试即可调用回退方法? (除了第一个请求会关闭电路)。

解决方案 将重试策略更改为仅处理ConnectionException即可解决此问题。

public RetryPolicy<Connection> retryPolicy(){
    return new RetryPolicy<>()
        .handle(ConnectionException.class)                
        .onFailedAttempt(e -> log.warn("Connection attempt to cache failed"))
        .withMaxRetries(2) //retry 2 times
        .withDelay(Duration.ofSeconds(5)); //every 5 seconds

}

0 个答案:

没有答案