SpringBootをご利用でしたら、https://github.com/spring-projects/spring-retry を導入するのが一番簡単です
※Spring-RetryはAOPの機能を使うので、spring-boot-starter-aopも必要です。
java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.retry.annotation.Backoff;
3import org.springframework.retry.annotation.Recover;
4import org.springframework.retry.annotation.Retryable;
5import org.springframework.stereotype.Repository;
6import org.springframework.transaction.annotation.Transactional;
7import org.sql2o.Connection;
8import org.sql2o.Sql2o;
9
10import lombok.extern.log4j.Log4j2;
11
12@Repository
13@Retryable
14public class SampleRepository {
15
16 @Autowired
17 Sql2o sql2o;
18
19 @Retryable(maxAttempts = 5, backoff=@Backoff(delay=5000), value = Exception.class)
20 @Transactional(readOnly = true)
21 public int findCount() {
22 String sql = "SELECT count(*) FROM sample1oo";
23
24 try (Connection con = sql2o.open()) {
25 return con.createQuery(sql).executeScalar(Integer.class);
26 }
27 }
28 @Recover
29 public int recover() {
30 log.warn("-- failure");
31 return -1;
32 }
33}
34
java
1import javax.sql.DataSource;
2
3import org.springframework.beans.factory.annotation.Autowired;
4import org.springframework.context.annotation.Bean;
5import org.springframework.context.annotation.Configuration;
6import org.springframework.jdbc.datasource.DataSourceTransactionManager;
7import org.springframework.retry.annotation.EnableRetry;
8import org.springframework.transaction.PlatformTransactionManager;
9import org.springframework.transaction.annotation.EnableTransactionManagement;
10import org.springframework.transaction.annotation.TransactionManagementConfigurer;
11import org.sql2o.Sql2o;
12
13@Configuration
14@EnableTransactionManagement
15@EnableRetry
16public class Sql2oConfig implements TransactionManagementConfigurer {
17
18 @Autowired
19 DataSource dataSource;
20
21 @Bean
22 public Sql2o sql2o() {
23 return new Sql2o(dataSource);
24 }
25
26 @Override
27 public PlatformTransactionManager annotationDrivenTransactionManager() {
28 return new DataSourceTransactionManager(dataSource);
29 }
30}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。