Design pattern for “retrying” logic that failed?

后端 未结 11 1344
挽巷
挽巷 2020-12-07 16:10

I\'m writing some reconnect logic to periodically attempt to establish a connection to a remote endpoint which went down. Essentially, the code looks like this:



        
11条回答
  •  醉话见心
    2020-12-07 16:51

    Shameless plug: I have implemented some classes to allow retrying operations. The library is not made available yet, but you may fork it on github. And a fork exists.

    It allows building a Retryer with various flexible strategies. For example:

    Retryer retryer = 
        RetryerBuilder.newBuilder()
                      .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECOND))
                      .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                      .retryIfExceptionOfType(IOException.class)
                      .build();
    

    And you can then execute a callable (or several ones) with the Retryer:

    retryer.call(new Callable() {
        public Void call() throws IOException {
            connection = newConnection();
            return null;
        }
    }
    

提交回复
热议问题