Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic response support for feign client

I am writing a REST client using Feign. There is an endpoint which can be generalized by parameterizing the path. But based on the path I can get a different type of response.

So I am trying to use a single method using generic. Since I must tell the method on the return type, I am parameterizing the type of the return value, like below,

@RequestLine("GET /objects/{type}/{model_id}")
public <T> Entity<T> getObject(
            @Param("type") String theObjectType, @Param("model_id") String theModelId,
            Class<T> theResponseClass);

But the problem is, Feign will use theResponseClass as body. How can I achieve a generic feign client method?

like image 422
Kannan Ramamoorthy Avatar asked Mar 27 '18 11:03

Kannan Ramamoorthy


People also ask

Which annotation is used to enable feign client?

A central concept in Spring Cloud's Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the @FeignClient annotation.

Can we use feign client without Eureka?

Yes you can use Feign without Ribbon, All you need to do is specify the base url in your Feign Java interface class.

Does feign client use RestTemplate?

Without Feign, in Spring Boot application, we use RestTemplate to call the User service. To use the Feign, we need to add spring-cloud-starter-openfeign dependency in the pom. xml file.

How do I pass multiple headers in feign client?

You need to use the annotation @RequestHeader in one of the parameters and pass the header along with it in the method declared inside Feign Interface. What if you want to send multiple headers? Just repeat the annotation!


1 Answers

You could just use Feigns' generic Response type. Sadly it's not typesafe and requires to return the body as inputStream or byte[].

Like this:

  @RequestLine("GET /objects/{type}/{model_id}")
  public Response getMyData(@Param("model_id") String theModelId)
  {
    return Response.Builder.body(response).build();
  }
like image 104
Laess3r Avatar answered Oct 06 '22 01:10

Laess3r