SpringBoot+Kotlinで外部APIへの接続が遅延した場合を想定して、ConnectTimeoutを起こしてみる。
呼び出し側
RestTemplateのConnectTimeoutを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のURLを存在しないIPアドレスに設定
application.yml
external:
task:
url: http://127.0.0.2
実行
http://localhost:8080/tasks/12345
2020-12-12 19:03:57.947 INFO 5809 --- [nio-8080-exec-3] c.e.b.controller.TasksController : getTask is called with taskId(12345).
2020-12-12 19:04:00.961 ERROR 5809 --- [nio-8080-exec-3] 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://127.0.0.2/tasks/12345": Connect timed out; nested exception is java.net.SocketTimeoutException: Connect timed out] with root cause
java.net.SocketTimeoutException: Connect timed out
at java.base/sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:546) ~[na:na]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:597) ~[na:na]
3秒経ってConnectTimeoutが発生するのを確認。
コメントを残す