天天看點

Retry重試機制

spring retry 重試機制

1.該重試需要引入jar包

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.1.2.RELEASE</version>
</dependency>
           

2.使用@Retryable和@Recover注解

@Retryable注解

被注解的方法發生異常時會重試

value:指定發生的異常進行重試

include:和value一樣,預設空,當exclude也為空時,所有異常都重試

exclude:指定異常不重試,預設空,當include也為空時,所有異常都重試

maxAttemps:重試次數,預設3

backoff:重試補償機制,預設沒有

@Backoff注解

delay:指定延遲後重試

multiplier:指定延遲的倍數,比如delay=5000l,multiplier=2時,第一次重試為5秒後,第二次為10秒,第三次為20秒

@Recover

當重試到達指定次數時,被注解的方法将被回調,可以在該方法中進行日志處理。需要注意的是發生的異常和入參類型一緻時才會回調

3.下面是test類

import com.ampmind.framework.service.exception.BizException;
import com.ampmind.framework.util.log.Logger;
import com.ampmind.framework.util.log.LoggerFactory;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * 測試重試機制的類
 *
 * @author Tonfu.Chia
 * @create 2017-07-26-下午1:51
 */
@EnableRetry
@Service
public class RetryService {
    private Logger logger = LoggerFactory.getLogger(RetryService.class);

    int count = ;

    @Retryable(maxAttempts = , backoff = @Backoff(delay = , multiplier = ), include = CanNotGetLockException.class)
    public void service() throws CanNotGetLockException {
        logger.info("", "重試第" + (count++) + "次。。。。。。");
        throw new CanNotGetLockException("重試異常");
    }

    @Recover
    public void recoverMethod(CanNotGetLockException e) {
        logger.info("", "資料恢複方法" + (count++));
    }

    class CanNotGetLockException extends BizException {

        public CanNotGetLockException() {
        }

        public CanNotGetLockException(String message) {
            super(message);
        }

        public CanNotGetLockException(Throwable cause) {
            super(cause);
        }

        public CanNotGetLockException(String message, String bizId) {
            super(message, bizId);
        }
    }
}