Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get headers feign netflix

I'm using netflix feign to communicate microservices.

So my Microservice A has an operation 'OperationA' which is consumed by the Microservice B and it passes one param by header named X-Total to B

 MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
 headers.add("X-Total", page.getTotalSize()); 

My client interface is as next:

@Headers({
    "Content-Type: " + MediaType.APPLICATION_JSON_UTF8_VALUE
})
@RequestLine("GET Dto/")
List<Dto> search();

static DtoClient connect() {
    return Feign.builder()
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())
        .target(ConditionTypeClient.class, Urls.SERVICE_URL.toString());
}

Then I've get the list of dto, but I don't know how to get the header X-TOTAL param:

public List<Dto> search() {
    DtoClient client = DtoClient.connect();
    return client.search();
}

How do I get the header params?

like image 716
Pau Avatar asked Jan 06 '23 14:01

Pau


1 Answers

Custom decoder

You could use a custom decoder:

public class CustomDecoder extends GsonDecoder {

    private Map<String, Collection<String>> headers;

    @Override
    public Object decode(Response response, Type type) throws IOException {
        headers = response.headers();
        return super.decode(response, type);
    }

    public Map<String, Collection<String>> getHeaders() {
        return headers;
    }
}

Return Response

Other solution could be return Response instead of List<Dto>:

@Headers({
    "Content-Type: " + MediaType.APPLICATION_JSON_UTF8_VALUE
})
@RequestLine("GET Dto/")
Response search();

Then deserialize body and get headers:

Response response = Client.search();
response.headers();
Gson gson = new Gson();
gson.fromJson(response.body().asReader(), Dto.class);
like image 161
cassiomolin Avatar answered Jan 15 '23 01:01

cassiomolin