0
0

kotlinでspring_retryを使ったサンプルをChatGPTを使用し作成

Last updated at Posted at 2023-12-23

概要

Kotlinのspring retryを使用したリトライ機能を実装していたが、実装に詰まったためChatGPTにサンプルを作成して問題解決を模索した。

ChatGPTとのやりとり

ChatGPTは3.5を使用した。
以下はやり取りを抜粋

kotlinでspring retryを使ったサンプルを作成

@Retryable(value = [SQLTransientConnectionException::class], maxAttempts = 3, backoff = Backoff(delay = 1000))
fun fetchDataFromDatabase(): List<String> {
    // データベースからデータを取得する処理
    // SQLTransientConnectionExceptionがスローされる可能性がある
}

fun main() {
    val data = fetchDataFromDatabase()
    println(data)
}

Spring Retryと@Asyncを使ったサンプルコードを出力して

@Component
class MyService {

    @Retryable(value = [SQLTransientConnectionException::class], maxAttempts = 3, backoff = Backoff(delay = 1000))
    @Async
    fun fetchDataFromDatabase(): List<String> {
        // データベースからデータを取得する処理
        // SQLTransientConnectionExceptionがスローされる可能性がある
    }
}

テストコードのサンプルを出力して

@SpringBootTest
class MyServiceTest {

    @Autowired
    lateinit var myService: MyService

    @MockBean
    lateinit var retryTemplate: RetryTemplate

    @Test
    fun `test fetchDataFromDatabase method with retry`() {
        val expectedData = listOf("data1", "data2", "data3")
        val retryAttempts = 3

        `when`(retryTemplate.execute(Mockito.any(RetryCallback::class.java)))
            .thenReturn(expectedData)

        val actualData: Future<List<String>> = myService.fetchDataFromDatabase()

        assertEquals(expectedData, actualData.get())
    }

    @Test
    fun `test fetchDataFromDatabase method with retry and exception`() {
        val retryAttempts = 3

        `when`(retryTemplate.execute(Mockito.any(RetryCallback::class.java)))
            .thenThrow(SQLTransientConnectionException::class.java)

        val actualData: Future<List<String>> = myService.fetchDataFromDatabase()

        assertEquals(null, actualData.get())
    }
}

終わりに

ChatGPT3.5を使用してコードのサンプルとテストコードのサンプルを作成し実装ソースと見比べることで問題解決を図った。

0
0
0

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
0
0