🙆‍♀️

WebClientにタイムアウトを設定する

2022/02/17に公開

サンプルコード

クライアント自体にタイムアウトを細かく設定するやり方もあるけれど、リクエスト単位でタイムアウトを指定するならこちらの方が簡単。

@RestController
public class WebClientController {

    private final WebClient webClient;

    @Autowired
    public WebClientController(WebClient.Builder builder) {
        webClient = builder.baseUrl("http://localhost:8080").build();
    }

    private Mono<String> get(String uri) {
        return webClient.get()
                .uri(uri)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(Duration.ofSeconds(10)); // ←←これ
    }

    @GetMapping
    public Mono<String> get() {
        return get("heavy");
    }
    
    @GetMapping("heavy")
    public ResponseEntity<String> getHeavy() {
        try {
            TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        return new ResponseEntity<>("OK", new HttpHeaders(), HttpStatus.OK);
    }

}
% time curl -i http://localhost:8080/
HTTP/1.1 500 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 17 Feb 2022 07:32:27 GMT
Connection: close

{"timestamp":"2022-02-17T07:32:27.046+00:00","status":500,"error":"Internal Server Error","path":"/"}
curl -i http://localhost:8080/  0.01s user 0.01s system 0% cpu 10.041 total

参考

Discussion