SpringBoot+Kotlinで外部APIの読み込みが遅延した場合を想定して、ReadTimeoutを起こしてみる。
呼び出し側
RestTemplateのReadTimeoutを3秒に設定
private var restTemplate: RestTemplate? = null
init {
restTemplate = restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(3))
.setReadTimeout(Duration.ofSeconds(3))
.build()
}
fun getTask(taskId: Int): Task? {
val uri = "$taskApiUrl/tasks/$taskId"
return restTemplate?.getForObject(uri, Task::class)
}
外部API側
リクエストを5秒間Sleepする外部APIを用意しておく。
@GetMapping("/{taskId}")
@ResponseBody
@ResponseStatus(HttpStatus.OK)
fun getTask(@PathVariable("taskId") taskId: Int): Task {
println("requst start for $taskId")
sleep(5000)
println("request end for $taskId")
return Task(
taskId = taskId,
title = "タスクのタイトル",
description = "タスクの詳細説明",
created = Date())
}
実行
http://localhost:8080/tasks/12345
2020-12-09 08:23:36.447 INFO 4147 --- [nio-8080-exec-6] c.e.b.controller.TasksController : getTask is called with taskId(12345).
2020-12-09 08:23:39.454 ERROR 4147 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:50000/tasks/12345": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out] with root cause
java.net.SocketTimeoutException: Read timed out
at java.base/sun.nio.ch.NioSocketImpl.timedRead(NioSocketImpl.java:283) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:309) ~
・・・省略・・・
3秒経ってReadTimeoutが発生するのを確認。
コメントを残す