Hint: Always define RestTemplate as a @Bean before autowiring [OK]
Common Mistakes:
Forgetting to create RestTemplate bean
Using incomplete URL
Misunderstanding getForEntity method
5. You want to call Service D from Service E using WebClient with a timeout of 2 seconds and handle errors gracefully. Which code snippet correctly implements this?
hard
A. WebClient client = WebClient.create("http://service-d/api");
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(2))
.onErrorReturn("Timeout or error")
.block();
B. WebClient client = WebClient.create();
String result = client.get()
.uri("http://service-d/api")
.retrieve()
.bodyToMono(String.class)
.block(Duration.ofSeconds(2));
C. RestTemplate restTemplate = new RestTemplate();
restTemplate.setTimeout(2000);
String result = restTemplate.getForObject("http://service-d/api", String.class);
D. WebClient client = WebClient.builder()
.baseUrl("http://service-d/api")
.build();
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.block();
Solution
Step 1: Setup WebClient with timeout and error handling
WebClient client = WebClient.create("http://service-d/api");
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(2))
.onErrorReturn("Timeout or error")
.block(); uses timeout(Duration.ofSeconds(2)) to limit wait time and onErrorReturn to provide fallback on errors.
Step 2: Verify other options
WebClient client = WebClient.create();
String result = client.get()
.uri("http://service-d/api")
.retrieve()
.bodyToMono(String.class)
.block(Duration.ofSeconds(2)); but uses block(Duration) which times out and throws an exception instead of providing a fallback; RestTemplate restTemplate = new RestTemplate();
restTemplate.setTimeout(2000);
String result = restTemplate.getForObject("http://service-d/api", String.class); tries to set timeout on RestTemplate incorrectly; WebClient client = WebClient.builder()
.baseUrl("http://service-d/api")
.build();
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.block(); lacks timeout and error handling.
Final Answer:
WebClient client = WebClient.create("http://service-d/api");
String result = client.get()
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(2))
.onErrorReturn("Timeout or error")
.block(); -> Option A