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

需要用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"值

阅读 10.2k
1 个回答

先回答一下:可以采用自定义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

望采纳。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进