Video in progress
How do you call another service with OpenFeign, and how are error responses handled?
You write an interface and annotate it with @FeignClient, and Spring Cloud generates the implementation. By default 4xx/5xx come out as FeignException, and with an ErrorDecoder you can turn them into your own exceptions.
📖 Answer
@SpringBootApplication
@EnableFeignClients
class OrderApp { }
@FeignClient(name = "inventory", url = "${clients.inventory.url}")
interface InventoryClient {
@GetMapping("/api/stock/{sku}")
StockDto stock(@PathVariable("sku") String sku);
@PostMapping("/api/reservations")
ReservationDto reserve(@RequestBody ReserveRequest req);
}
In a service it's injected like an ordinary bean: inventoryClient.stock("A-17").
Making the errors your own:
@Bean
ErrorDecoder inventoryErrors() {
return (methodKey, response) -> switch (response.status()) {
case 404 -> new ProductNotFoundException(methodKey);
case 409 -> new OutOfStockException();
default -> new ErrorDecoder.Default().decode(methodKey, response);
};
}
Settings that get forgotten:
- timeouts:
spring.cloud.openfeign.client.config.inventory.connect-timeoutandread-timeout. Without them, a slow service ties up your threads; - be careful with retry: resending a POST may book twice;
- write the name explicitly in
@PathVariable("sku").
For a new project: Spring Cloud OpenFeign is now "feature complete" and gets no new features. Spring 6 itself has the same declarative style: @HttpExchange interfaces with RestClient. In new code people mostly pick that.
Sign up to mark studied questions and save your progress.