LoginSignup
20
17

More than 3 years have passed since last update.

Spring-Retryでリトライ処理の実装

Last updated at Posted at 2019-05-07

はじめに

(DBへの)データ登録の失敗時にリトライ処理を入れたい場合があり、その際に、Spring-Retryでリトライ処理を実装してみましたので、メモを残しておきます。

今回は例として、unique制約のあるカラムにデータをinsertする際に、同じ値があればリトライするというケースです。

下準備

①build.gradleのdependenciesに以下を追記し、Spring-Retryを追加


compile('org.springframework.retry:spring-retry')
compile('org.springframework.boot:spring-boot-starter-aop')

②利用したい@Configurationなクラスに@EnableRetryを追加

@Configuration
@EnableRetry
public class AppConfig { ... }

リトライ処理

Retryable

下記のサンプルのように@Retryableをつける事により、UniqueConstraintExceptionが発生した際は(デフォルトで上限3回まで)リトライするようにしています。

@Retryable(value = { UniqueConstraintException.class })
public void retryService() throws UniqueConstraintException {
  this.dao.insert("hash化された文字列が入るよ!");
}

また、maxAttemptsを設定し、3回以上リトライすることもできる。
※下記の例では5回リトライしている

@Retryable(value = { UniqueConstraintException.class }, maxAttempts = 5)

他にもリトライの間隔をbackoffで指定できたり、複数のExceptionを扱うこともできます。


@Retryable(value = { UniqueConstraintException.class, HogeException.class }, maxAttempts = 5, backoff = @Backoff(delay = 5000))

Recover

指定された回数をリトライ後に、さらにUniqueConstraintExceptionが発生して場合には、@Recoverを追加した関数が呼び出される

@Recover
public void recover(UniqueConstraintException e) {
  // ... do something
}

参考

https://www.baeldung.com/spring-retry
https://github.com/spring-projects/spring-retry

20
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
17