【问题标题】:Get headers feign netflix获取标题 feign netflix
【发布时间】:2016-12-09 02:13:02
【问题描述】:

我正在使用netflix feign 与微服务通信。

所以我的微服务 A 有一个操作 'OperationA' 由微服务 B 使用,它通过名为 X-Total 的标头将一个参数传递给 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的列表,但是我不知道如何获取header X-TOTAL参数:

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

如何获取标题参数?

【问题讨论】:

    标签: java web-services spring-cloud-netflix netflix-feign


    【解决方案1】:

    自定义解码器

    您可以使用自定义解码器:

    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;
        }
    }
    

    返回响应

    其他解决方案可以是返回响应而不是List&lt;Dto&gt;

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

    然后反序列化body并获取headers:

    Response response = Client.search();
    response.headers();
    Gson gson = new Gson();
    gson.fromJson(response.body().asReader(), Dto.class);
    

    【讨论】:

    • 我已经使用了您之前的建议:将我的 search() 方法更改为返回响应,然后获取标题并解析正文。它工作正常!这个主意也不错,
    • @PauChorro 我最终删除了该评论。但是这两种方法都应该有效:)
    • 对于第一个选项(自定义解码器),那么如何使用feign客户端从代码中访问解码器的getHeaders()方法?
    【解决方案2】:

    我迟到了,但我知道这对将来的某个人会有所帮助

    我们可以将response 包装成ResponseEntity&lt;SomePojo&gt;,这样我们就可以作为headers 对象作为body 对象访问,类型为SomePojo

    ...
    import org.springframework.http.ResponseEntity;
    ...
    
    
    public ResponseEntity<List<Dto>> search() {
        DtoClient client = DtoClient.connect();
        return client.search();
    }
    

    【讨论】:

    • 这比使用自定义解码器更容易
    猜你喜欢
    • 2019-07-27
    • 2017-10-01
    • 1970-01-01
    • 2018-02-01
    • 2018-09-24
    • 2015-02-08
    • 2020-08-13
    • 2016-02-06
    • 2019-12-02
    相关资源
    最近更新 更多