- 编写Decoder (内部使用方式一的Gzip解压缩工具类GzipUtils)
public class FeignResponseDecoder implements Decoder {private final Decoder delegate;public FeignResponseDecoder(Decoder delegate) {Objects.requireNonNull(delegate, "Decoder must not be null. ");this.delegate = delegate;}@Overridepublic Object decode(Response response, Type type) throws IOException {Collection values = response.headers().get(HttpEncoding.CONTENT_ENCODING_HEADER);if (Objects.nonNull(values) && !values.isEmpty() && values.contains(HttpEncoding.GZIP_ENCODING)) {byte[] compressed = Util.toByteArray(response.body().asInputStream());if ((compressed == null) || (compressed.length == 0)) {return delegate.decode(response, type);}//decompression part//after decompress we are delegating the decompressed response to default//decoderif (isCompressed(compressed)) {String decompressValue = GzipUtils.decompress(compressed);Response decompressedResponse = response.toBuilder().body(decompressValue.getBytes()).build();return delegate.decode(decompressedResponse, type);} else {return delegate.decode(response, type);}} else {return delegate.decode(response, type);}}private static boolean isCompressed(final byte[] compressed) {return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));}
}
- 将Decoder加入到Spring容器管理
@Configuration
public class AppConfig{@Beanpublic Decoder GZIPResponseDecoder(ObjectFactory messageConverters) {Decoder decoder = new FeignResponseDecoder(new SpringDecoder(messageConverters));return decoder;}
}
- feign接口使用普通java对象接收数据
@FeignClient(contextId = "testFeignClient", name = "client-a", configuration = FeignConfig.class)
public interface TestFeignClient {@GetMapping("/userInfo")UserInfoVO userInfo(@RequestParam("username") String username, @RequestParam("address") String address) ;
}
- 编写单元测试
@Slf4j
public class TestFeignClientTest extends BaseJunitTest {@Autowiredprivate TestFeignClient testFeignClient ;@Testpublic void userInfo(){String username = "张三" ;String address = "北京" ;UserInfoVO userInfo = testFeignClient.userInfo(username, address);log.info("user info : {}", userInfo);}
}