Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feign REST Client: How to get the HTTP status?

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?

like image 740
oneCoderToRuleThemAll Avatar asked Jun 26 '19 20:06

oneCoderToRuleThemAll


People also ask

How do I create a restcontroller with feignclient?

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.

Does @feignclient need the URL attribute?

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.

What is feign API client?

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.

How to create a feign REST client in Spring Framework?

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.


1 Answers

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();
like image 121
Muhammad Usman Avatar answered Nov 08 '22 02:11

Muhammad Usman