本文内容主要来自
http://www.itmuch.com/spring-cloud-sum/feign-problems/
1、什么是Feign
声明式http客户端
2、如何使用
加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
加注解
@EnableFeignClients
加配置
无写代码
package com.fj.xiaofeiyang.pay.api.feignclient;
import com.fj.xiaofeiyang.pay.api.domain.entity.pay.MallPay;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 19:17
*/
@FeignClient(name = "pay")
public interface PayFeignClient {
@GetMapping("/mallpay/{id}")
MallPay findById(@PathVariable("id") Integer id);
}
feign的组成
接口 | 作用 | 默认值 |
Feign.Builder | Feign的入口 | Feign.Builder |
Client | Feign底层用什么去发起请求 | 和Ribbon配合时:LoadBalancerFeignClient,不和Ribbon配合时feign.Client.Defualt |
Contract | 锲约支持 | Feign不支持springMVC注解,SpringMvcContract |
Encoder | 编码器,用于将对象转换成http消息体 | SpringEncoder |
Decoder | 解码器,将响应消息体转换成对象 | ResponseEntityDecoder |
Logger |
日志管理器 | Slf4jLogger |
RequestInterceptor |
用于为每个请求添加通用逻辑 | 无 |
Feign日志
级别 | 打印内容 |
NONE默认值 | 不记录日志 |
BASIC | 仅记录请求方法、URL、响应状态代码以及执行时间 |
HEADERS | 记录BASIC级别的基础上,记录请求和响应的header |
FULL | 记录请求和响应的header、body和元数据 |
自定义日志级别
package com.fj.xiaofeiyang.pay.api.feignclient;
import com.fj.xiaofeiyang.pay.api.configuration.PayFeignClientConfiguration;
import com.fj.xiaofeiyang.pay.api.domain.entity.pay.MallPay;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 19:17
*/
@FeignClient(name = "pay",configuration = PayFeignClientConfiguration.class)
public interface PayFeignClient {
@GetMapping("/mallpay/{id}")
MallPay findById(@PathVariable("id") Integer id);
}
package com.fj.xiaofeiyang.pay.api.configuration;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: yangchun
* @description:
* @date: Created in 2020-02-19 20:42
*/
@Configuration
public class PayFeignClientConfiguration {
@Bean
public Logger.Level logLevel(){
return Logger.Level.BASIC;
}
}
logging:
level:
com.fj.xiaofeiyang.pay.api.feignclient.PayFeignClient: debug
feign日志时建立再包必须输出日志上的,所以必须有debug
属性配置如下
feign:
client:
config:
pay:
loggerLevel: full
以上都是细粒度配置
全局配置两种方式
java代码方式
第一种添加Configuration,父子上下文重叠
第二种
@EnableFeignClients(defaultConfiguration = PayFeignClientConfiguration.class)
配置属性全局配置
feign:
client:
config:
#全局配置
default:
loggerLevel: full
支持的配置项
java代码方式
配置项 | 作用 |
Logger.level |
指定日志级别 |
Retryer |
指定重试策略 |
ErrorDecodre |
指定错误解码器 |
Request.options |
超时 |
Collection<RequestInterceptor> |
拦截器 |
SelectFactory |
用于设置Hystrix配置属性,Feign整合Hystrix才会使用 |
属性配置方式支持的配置项
feign:
client:
config:
#全局配置
default:
loggerLevel: full
connectionTimeout: 5000
readTimeout: 5000
errerDecoder: com.demo.decoder
retryer: com.demo.retryer
requestInterceptors:
- com.demo.FooRequestInterceptor
decode404: false
encoder: com.demo.encoder
decoder: com.demo.decoder
contract: com.demo.Contract
Feign多参数请求
1、GET
@GetMapping("/q")
List<MallPay> query(@SpringQueryMap MallPay mallPay);
第一种不支持继承
@GetMapping("/q")
List<MallPay> query1(@RequestParam("id") Integer id);
@GetMapping("/q")
List<MallPay> query2(@RequestParam Map<String,Object> mallPay);
@GetMapping("/q")
public List<MallPay> query(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
@GetMapping("/q")
public List<MallPay> query1(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
@GetMapping("/q")
public List<MallPay> query2(MallPay mallPay){
return mallPayMapper.select(mallPay);
}
2、POST
@RequestMapping(value="/q3",method = RequestMethod.POST)
List<MallPay> query3(@RequestBody MallPay mallPay);
Feign 脱离Ribbon使用如下
@FeignClient(name = "baidu",url = "http://www.baidu.com")
public interface BaiduFeignClient {
@GetMapping
public String index();
}
Feign和RestTemplate对比
角度 | RestTemplate | Feign |
可读性、可维护性 | 一般 | 极好 |
开发体验 | 欠佳 | 极佳 |
性能 | 很好 | 中等RestTemplate50% |
灵活性 | 极佳 | 中等内置功能可满足绝大多数需求 |
Feign的性能优化
1、配置连接池,性能提升15%
2、apache http client 或者okhttp client,下面两个依赖二选一
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>10.7.4</version>
</dependency>
配置也是二选一
feign:
client:
config:
#全局配置
default:
loggerLevel: full
httpclient:
enable: true
#最大连接数
max-connection: 200
#单个路径最大连接数
max-connection-per-route: 50
okhttp:
enable: true
max-connection: 200
#单个路径最大连接数
max-connection-per-route: 50
3、日志级别最好设置成basic
Feign的常见问题
1、使用案例
使用Feign上传文件
加依赖
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.0.3</version>
</dependency>
写FeignClient
注意点
-
中的
produeces
、consumes
不能少; -
接口定义中的注解
@RequestPart(value = "file")
不能写成@RequestParam(value = "file"
。 -
最好将Hystrix的超时时间设长一点,例如5秒,否则可能文件还没上传完,Hystrix就超时了,从而导致客户端侧的报错。
使用Feign提交Form表单
加依赖
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.2.2</version>
</dependency>
编写FeignClient
2、FeignClient接口使用@PathVariable,必须指定value属性
@FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) public User findById(@PathVariable("id") Long id); ... }
3、Java自定义配置类要防止父子上下文重叠
4、Feign注解属性
@FeignClient(name = "microservice-provider-user")
在早期的Spring Cloud版本中,无需提供name属性,从Brixton版开始,@FeignClient必须提供name属性,否则应用将无法正常启动!
另外,name、url等属性支持占位符。例如:
@FeignClient(name = "${feign.name}", url = "${feign.url}")
5、类级别的RequestMapping会被SpringMVC加载
@RequestMapping("/users") @FeignClient(name = "microservice-user") public class TestFeignClient { // ... }
类上的@RequestMapping
注解也会被Spring MVC加载。该问题现已经被解决,早期的版本有两种解决方案:
方案1:不在类上加@RequestMapping
注解;
方案2:添加如下代码:
@Configuration @ConditionalOnClass({ Feign.class }) public class FeignMappingDefaultConfiguration { @Bean public WebMvcRegistrations feignWebRegistrations() { return new WebMvcRegistrationsAdapter() { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new FeignFilterRequestMappingHandlerMapping(); } }; } private static class FeignFilterRequestMappingHandlerMapping extends RequestMappingHandlerMapping { @Override protected boolean isHandler(Class<?> beanType) { return super.isHandler(beanType) && !beanType.isInterface(); } } }
6、首次请求失败
一、将Hiystrix超时时间设置长
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
二、禁止使用Hystrix超时
hystrix.command.default.execution.timeout.enabled: false
三、feign全局禁止使用Hystrix
feign.hystrix.enabled: false
局部禁止使用Hystrix
四、为ribbon配置饥饿加载
ribbon:
eager-load:
enabled: true
clients: client1, client2, client3
7、产生Hystrix监控信息
Feign本身已经整合了Hystrix,可直接使用@FeignClient(value = "microservice-provider-user", fallback = XXX.class)
来指定fallback类,fallback类继承@FeignClient所标注的接口即可。
但是假设如需使用Hystrix Stream进行监控,默认情况下,访问http://IP:PORT/actuator/hystrix.stream
是会返回404,这是因为Feign虽然整合了Hystrix,但并没有整合Hystrix的监控。如何添加监控支持呢?需要以下几步:
第一步:添加依赖,示例:
<!-- 整合hystrix,其实feign中自带了hystrix,引入该依赖主要是为了使用其中的hystrix-metrics-event-stream,用于dashboard --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
第二步:在启动类上添加@EnableCircuitBreaker
注解,示例:
@SpringBootApplication @EnableFeignClients @EnableDiscoveryClient @EnableCircuitBreaker public class MovieFeignHystrixApplication { public static void main(String[] args) { SpringApplication.run(MovieFeignHystrixApplication.class, args); } }
第三步:在application.yml中添加如下内容,暴露hystrix.stream端点:
management: endpoints: web: exposure: include: 'hystrix.stream'
这样,访问任意Feign Client接口的API后,再访问http://IP:PORT/actuator/hystrix.stream
,就会展示一大堆Hystrix监控数据了。