6 months ago

spring-retry 非常的好用,可以基於 Exception 來判斷要不要重試,所以遇上網路不穩的環境時就可以省力許多

dependencies 要加上 spring-retry

build.gradle
dependencies {
    compile('org.springframework.retry:spring-retry')
}

主程式要啟動 EnableRetry

KpiApplication.java
@EnableRetry
@SpringBootApplication
public class KpiApplication {

    public static void main(String[] args) {
        SpringApplication.run(KpiApplication.class, args);
    }
}

實際使用

PasswdForgetService.java
@Service
public class PasswdForgetService {

    @Autowired
    @Qualifier("OAuthOperateImplOKHttp")
    private HttpOperate httpOperate;

    @Retryable(value = {RemoteAccessException.class, ConnectException.class},
            maxAttempts = 2,
            backoff = @Backoff(value = 2000))
    public void forgetCreate(PasswdForgetDto passwdForgetDto) throws Exception {
        CustomResponse customResponse = null;
        try {
            customResponse = httpOperate.postjson("http://localhost:8082/api/v1/passwordforget", passwdForgetDto);
        } catch (Exception e) {
            throw e;
        }
    }

    @Recover
    public void recover1(RemoteAccessException e) {
        System.out.println(e.getMessage());
        System.out.println("do recover operation1");
    }

    @Recover
    public void recover1(ConnectException e) {
        System.out.println(e.getMessage());
        System.out.println("do recover operation2");
    }
}

說明:
Retryable 就是 Spring Retry 提供的註解

當捕捉到 RemoteAccessException 跟 ConnectException 的時候表示我們可能處在網路不穩的狀況,說不定等等重試就好了

maxAttempts 表示最多執行兩次

backoff 表示間隔,當捕捉到錯誤時,停多就重試

@Recover 則是定義該錯誤的處理,只能寫在同一個 Class 裡面喔

結束~~

是不是超簡單又實用

← SpringBoot Build War use spring-security protect ResourceServer →
 
comments powered by Disqus