RetryNTimes extends AbstractRetryTemplate<V> { @Override public V execute(Command<V> command) throws Exception { for (int i = 0; n == -1 || i <= n; i++) { if(destroyed.get()){ logger.info("[execute][destroyed return null]{}", this); return null; } if (i >= 1) { logger.info("[execute][retry]{}, {}", i, command); retryPolicy.retryWaitMilli(true); } if(destroyed.get()){ logger.info("[execute][destroyed return null]{}", this); return null; } try { logger.debug("[execute]{}, {}", i, command); CommandFuture<V> future = command.execute(); if(future == null){ return null; } return future.get(retryPolicy.waitTimeoutMilli(), TimeUnit.MILLISECONDS); } catch (Exception e) { if (isLogDetail()) { logger.warn(String.format("cmd:%s, message:%s", command, e.getMessage()), e); } Exception originalException = getOriginalException(e); if (i == n || !retryPolicy.retry(originalException)) { throw originalException; } } command.reset(); } return null; } RetryNTimes(int n, int delayBaseMilli);  RetryNTimes(int n);  RetryNTimes(int n, RetryPolicy retryPolicy);  RetryNTimes(int n, RetryPolicy retryPolicy, boolean logDetail); static RetryTemplate<V> retryForEver(RetryPolicy retryPolicy); static RetryTemplate<V> noRetry(); @Override V execute(Command<V> command); @Override void destroy();  }
@Test public void testSuccess() throws Exception{ RetryNTimes<Object> retryNTimes = new RetryNTimes<Object>(100, new RetryDelay(100)); Assert.assertNotNull(retryNTimes.execute(new TestRetryCommand(new Object()))); }
@Test public void testFailRetry() throws Exception{ int retryTimes = 3; RetryDelay retryDelay = new RetryDelay(100); RetryNTimes<Object> retryNTimes = new RetryNTimes<Object>(retryTimes, retryDelay); try { retryNTimes.execute(new TestRetryCommand(new Exception("just fail"))); } catch (Exception e) { Assert.assertEquals(3, retryDelay.getRetryTimes()); Assert.assertEquals("just fail", e.getMessage()); } }
@Test public void testFailNoRetry() throws Exception{ RetryPolicy retryPolicy = new RetryExceptionIsSuccess(100); RetryNTimes<Object> retryNTimes = new RetryNTimes<Object>(3, retryPolicy); try { retryNTimes.execute(new TestRetryCommand(new Exception("just fail"))); } catch (Exception e) { Assert.assertEquals(0, retryPolicy.getRetryTimes()); Assert.assertEquals("just fail", e.getMessage()); } }