Spring Bootでspring-retryを使って処理をリトライする方法(@EnableRetryと@Retryableと@Recover)
Spring Bootである処理を指定した回数分リトライしたい、と言った場合はあまり知られていないと思うのですがspring-retryを使うと簡単に実装することができます。
build.gradleのdependenciesに以下を追記します。
implementation 'org.springframework.retry:spring-retry' implementation 'org.springframework.boot:spring-boot-starter-aop'
リトライしたいクラスに@EnableRetryを付与します。
リトライしたいメソッドに@Retryableアノテーションを付与します。
@Retryable(value= {Exception.class}, maxAttempts = 5, backoff=@Backoff(delay=1000))
valueに{}で例外を指定します。
複数指定する場合はカンマ区切りで指定します maxAttemptsはリトライ回数です。ここでは5回です。
backoffは@Backoff(delay=1000)とすることによってリトライ間隔を指定します。
単位はミリ秒なのでここでは1秒です。
とりあえずリトライされるか試したいだけなので以下のようなメインにします。
package jp.co.confrage;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
@SpringBootApplication
@EnableRetry
public class SpringRetryApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(SpringRetryApplication.class, args);
}
@Override
@Retryable(value= {Exception.class}, maxAttempts = 5, backoff=@Backoff(delay=1000))
public void run(String... args) throws Exception {
System.out.println("通る");
throw new Exception(); // ここで必ず例外発生するので、リトライする
}
}
実行すると1秒おきに5回リトライされて6回目の例外時はエラーとなっているのが確認できます。
でもこの動きちょっとまずくない?という場合に@Recoverアノテーションを付与したメソッドを作成して、6回目のリトライエラー時の回避メソッドを作成することができます。
package jp.co.confrage;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
@SpringBootApplication
@EnableRetry
public class SpringRetryApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(SpringRetryApplication.class, args);
}
@Override
@Retryable(value= {Exception.class}, maxAttempts = 5, backoff=@Backoff(delay=1500))
public void run(String... args) throws Exception {
System.out.println("通る");
throw new Exception();
}
@Recover
public void reco(Exception exception) {
System.out.println("6回目に通る");
}
}
recoメソッドに@Recoverアノテーションを付与しました。メソッド名は何でもよいです。
@Retryableと同じクラスに@Recoverアノテーションを付与したメソッドがあればよいです。
今回はリトライ間隔を1.5秒にしました。
6回目例外発生時に@Recoverアノテーションが付与されたメソッドが実行されることが確認できます。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^




コメント