我正在使用 netflix feign沟通微服务。
所以我的微服务 A 有一个操作“OperationA”,它被微服务 B 使用,它通过名为 X-Total 的 header 将一个参数传递给 B
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("X-Total", page.getTotalSize());
我的客户端界面如下:
@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());
}
然后我得到了 dto 的列表,但我不知道如何获取标题 X-TOTAL 参数:
public List<Dto> search() {
DtoClient client = DtoClient.connect();
return client.search();
}
如何获取 header 参数?
最佳答案
自定义解码器
您可以使用自定义解码器:
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;
}
}
返回响应
其他解决方案可能是返回 Response 而不是 List<Dto>
:
@Headers({
"Content-Type: " + MediaType.APPLICATION_JSON_UTF8_VALUE
})
@RequestLine("GET Dto/")
Response search();
然后反序列化正文并获取 header :
Response response = Client.search();
response.headers();
Gson gson = new Gson();
gson.fromJson(response.body().asReader(), Dto.class);
关于java - 获取标题假装 netflix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38742191/