I have Feign client setup with Hystrix and I am trying to log all the HTTP status codes that I get from my API calls into a database. So this means, if one of my calls give me a 201, I would want to log that into DB. If my call results in a failure, my fallback handler can obviously log that but I want to do the DB inserts in one place. Does feign have a way to get access to responses or some kind of general callback?
I will create a RestController with only one method which makes use of FeignClient. To use Feign client you will need to Autowire it to your Controller class or a Service method. In the example above TodoClient is being Autowired to my RestController.
Its just a http client implementation. So you do need to provide the URL it needs to connect to. Most of the answers suggest putting the url attribute to @FeignClient, but when the architecture involves registering the service ( Eureka Client) with the Eureka Server, I think, there is no liberty to use the url attribute.
Feign aims at simplifying HTTP API clients. Simply put, the developer needs only to declare and annotate an interface while the actual implementation will be provisioned at runtime. 2. Example We will present an example of a bookstore service REST API, that is queried and tested based on the Feign HTTP client.
To create a new Feign REST Client we need to create a new Java interface and annotated it with @FeignClient annotation. No need to provide implementation for this interface. Spring Framework and Feign will provide an implementation for this interface for us at runtime.
You have to provide custom decoder
to get your response in ResponseEntity<Object>
.
NotificationClient notificationClient = Feign.builder()
.encoder(new JacksonEncoder())
.decoder(customDecoder())
.target(Target.EmptyTarget.create(NotificationClient.class));
Here you define your custom decoder bean. You can define your own by implementing Decoder
but I'm using spring decoder.
@Bean
public Decoder customDecoder() {
HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper());
ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}
Now collect your response in ResponseEntity<Object>
ResponseEntity<Object> response = notificationClient.notify();
int status = response.getStatusCodeValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With