본문 바로가기

emotional developer/detect-Java

spring retry 간단 예제.


1.

우선 라이브러리 부터 추가.

maven > pom.xml


<dependency>

<groupId>org.springframework.retry</groupId>

<artifactId>spring-retry</artifactId>

<version>1.0.3.RELEASE</version>

</dependency>



2.

실제 적용 코드

blabla.java


public class blabla implements InitializingBean {

static final String KEY = "testKey";

private RetryTemplate retryTemplate;

      private RetryCallback<Long> retryCallback;

private Client client;


@Autowired

public blabla(Client client) {

this.client= client;

}


public void setRetryTemplate(RetryTemplate retryTemplate) {

this.retryTemplate = retryTemplate;

}


@Override

public void afterPropertiesSet() throws Exception {

retryTemplate = new RetryTemplate();


// 전체 시도 시간 기준 ex) 3초 동안 횟수 제한 없이 시도한다.

// TimeoutRetryPolicy timeoutRetryPolicy = new TimeoutRetryPolicy();

// timeoutRetryPolicy.setTimeout(3000L);


// 전체 시도 횟수 기준 ex) 3회 시도 한다.

int maxAttempts = 3;

// Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();

// retryableExceptions.put(Exception.class, true);

// SimpleRetryPolicy aa = new SimpleRetryPolicy(maxAttempts, retryableExceptions);


SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();

simpleRetryPolicy.setMaxAttempts(maxAttempts);


retryTemplate.setRetryPolicy(simpleRetryPolicy);


retryCallback = new RetryCallback<Long>() {

public Long doWithRetry(RetryContext context) throws RuntimeException {

return getNewLogNo();

}

};

}


/**

* @return

*/

Long getNewNo() {

final Long newNo = client.increment(KEY);

if (newNo == null) {

throw new RuntimeException("getNewNo : new no is null.");

}

return newNo;

}


/**

* @return

*/

public Long getNewNoWithRetry() throws RuntimeException {

return retryTemplate.execute(retryCallback);

}










반응형