|
@@ -0,0 +1,76 @@
|
|
|
+---
|
|
|
+title: 接口请求工具 - Feign
|
|
|
+date: 2020-06-03 10:26:17
|
|
|
+tags: [Java,Http]
|
|
|
+categories: [Java,Utils]
|
|
|
+---
|
|
|
+
|
|
|
+### 接口请求工具
|
|
|
+
|
|
|
+在微服务还未盛行的时候,一般服务间的请求使用的底层方式: jdk自带的HttpURLConnection 或者 封装的Apache HttpClient / Okhttp 等框架,微服务盛行后优秀的请求框架 Feign 被Spring看中 推荐成了微服务体系里面的请求工具,有着简洁 效率 易读 侵虐性低等优点。本文主要介绍剥离开Spring框架使用Feign,或者在Spring中调用未接入微服务注册中心的服务/系统。
|
|
|
+
|
|
|
+[Git 地址](https://github.com/OpenFeign/feign)
|
|
|
+
|
|
|
+#### Feign配置
|
|
|
+
|
|
|
+```
|
|
|
+// 设置不格式化json
|
|
|
+ ObjectMapper mapper = new ObjectMapper().disable(SerializationFeature.INDENT_OUTPUT);
|
|
|
+ JacksonDecoder decoder = new JacksonDecoder();
|
|
|
+ // json 编码 并兼容表单提交方式
|
|
|
+ FormEncoder formEncoder = new FormEncoder(new JacksonEncoder(mapper));
|
|
|
+ // 包含熔断器的builder
|
|
|
+ HystrixFeign.Builder builder = HystrixFeign.builder()
|
|
|
+ // 设置底层实现形式 提高效率
|
|
|
+ .client(new OkHttpClient())
|
|
|
+ // 请求连接时间 请求等待时间
|
|
|
+ .options(new Request.Options(10000, 120000))
|
|
|
+ // 重试机制
|
|
|
+ .retryer(new Retryer.Default(5000, 5000, 3))
|
|
|
+ .encoder(formEncoder).decoder(decoder)
|
|
|
+ .logger(new Slf4jLogger());
|
|
|
+ }
|
|
|
+```
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+#### Get 请求
|
|
|
+
|
|
|
+```java
|
|
|
+public interface IGetFeign {
|
|
|
+ @RequestLine("GET /xxxxx?param={id}")
|
|
|
+ UserVO getXXXById(@Param("id") Long id);
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+可以使用@QueryMap 注解查询多个参数
|
|
|
+
|
|
|
+#### POST 请求
|
|
|
+
|
|
|
+```java
|
|
|
+public interface IPostFeign {
|
|
|
+ @RequestLine("POST /xxx/save")
|
|
|
+ Boolean save(Map data, @HeaderMap Map<String, String> headerMap);
|
|
|
+
|
|
|
+ @RequestLine("POST /xxx/get_product")
|
|
|
+ @Headers("Content-Type: application/x-www-form-urlencoded")
|
|
|
+ Product getProductInfo(@Param("id") Long id);
|
|
|
+}
|
|
|
+```
|
|
|
+
|
|
|
+可以使用 @Headers() 单独添加头信息 变量可以使用 @Param 注解传入,或者 使用 @HeaderMap 添加多个头信息;默认使用json编码传输,可以通过头信息来指定content-type传输,或者使用 @Body 注解直接书写传输内容
|
|
|
+
|
|
|
+#### 使用
|
|
|
+
|
|
|
+```java
|
|
|
+IPostFeign feign = builder.target(IPostFeign.class, "productAddress", fallbackFactory);
|
|
|
+Product product = feign.getProductInfo(1L);
|
|
|
+```
|
|
|
+
|
|
|
+使用了熔断器的话 需要写个fallback类 继承 FallbackFactory
|
|
|
+
|
|
|
+#### Spring中使用
|
|
|
+
|
|
|
+把Feign配置使用@Configuration注解,并把targer生成的对象 添加 @Bean注解 添加到容器中,在使用的地方注入即可
|