Feign调用接口要怎么获取到被调用接口headers的值

发布于 2022-09-11 21:25:31 字数 496 浏览 22 评论 0

需要用backend的微服务去调用store服务的接口:

@RequestMapping(method = RequestMethod.GET, value = "/api/get-store-list")
List<store> getStoreList();

而在store的getStoreList接口,查询了store的接口数据,同时把list的总条数放在了接口的headers里面:

Page<Store> storePage = storeRepo.findAll(pageable);
response.addHeader("X-Total-Count", totalElements + "");

这样接口返回list的同时就能直接获取list的总条数。

但是现在用Feign的方式去调用,那要怎么才能获取到getStoreList()接口headers里面的"X-Total-Count"值

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的心爱 2022-09-18 21:25:31

先回答一下:可以采用自定义Decoder的方式实现。具体实现很多,稍微找个例子https://stackoverflow.com/que...

实现所基于的原理如下:
Feign 远程服务本地化调用,会将返回的信息decode成对应Response Bean.

在接口定义上Feign做的比较简单,抽象出了Encoder 和decoder 接口,其中decoder接口

public interface Decoder {

  /**
   * Decodes an http response into an object corresponding to its {@link
   * java.lang.reflect.Method#getGenericReturnType() generic return type}. If you need to wrap
   * exceptions, please do so via {@link DecodeException}.
   *  从Response 中提取Http消息正文,通过接口类声明的返回类型,消息自动装配
   * @param response the response to decode 
   * @param type     {@link java.lang.reflect.Method#getGenericReturnType() generic return type} of
   *                 the method corresponding to this {@code response}.
   * @return instance of {@code type}
   * @throws IOException     will be propagated safely to the caller.
   * @throws DecodeException when decoding failed due to a checked exception besides IOException.
   * @throws FeignException  when decoding succeeds, but conveys the operation failed.
   */
  Object decode(Response response, Type type) throws IOException, DecodeException, FeignException;

  /** Default implementation of {@code Decoder}. */
  public class Default extends StringDecoder {

    @Override
    public Object decode(Response response, Type type) throws IOException {
      if (response.status() == 404) return Util.emptyValueOf(type);
      if (response.body() == null) return null;
      if (byte[].class.equals(type)) {
        return Util.toByteArray(response.body().asInputStream());
      }
      return super.decode(response, type);
    }
  }
}

可以看到decode方法中就可以通过response.headers()方式获取到http headers

望采纳。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文