1、spring cloud feign概述
在前面的文章中,负载均衡组件ribbon介绍中,可以发现当我们通过RestTemplate调用其它服务的API时,所需要的参数须在请求的URL中进行拼接,如果参数少的话或许我们还可以忍受,一旦有多个参数或者调用多个API时,代码上就显得比较冗余了。为了克服这些不足,Spring Cloud提供了声明式调用组件—Feign。
Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。
而Feign则会完全代理HTTP请求,我们只需要像调用方法一样调用它就可以完成服务请求及相关处理。Feign整合了Ribbon和Hystrix,可以让我们不再需要显式地使用这两个组件。
总起来说,Feign具有如下特性:
- 可插拔的注解支持,包括Feign注解和JAX-RS注解;
- 支持可插拔的HTTP编码器和解码器;
- 支持Hystrix和它的Fallback;
- 支持Ribbon的负载均衡;
- 支持HTTP请求和响应的压缩。
2、feign原理解析
- 启动时,程序会进行包扫描,扫描所有包下所有@FeignClient注解的类,并将这些类注入到spring的IOC容器中。当定义的Feign中的接口被调用时,通过JDK的动态代理来生成RequestTemplate。
- RequestTemplate中包含请求的所有信息,如请求参数,请求URL等
- RequestTemplate生成Request,然后将Request交给client处理,这个client默认是JDK的HTTPUrlConnection,也可以是OKhttp、Apache的HTTPClient等
- 最后client封装成LoadBaLanceClient,结合ribbon负载均衡地发起调用
2.1 产品原理图
2.2 相关模块
Feign是一个完整的工程项目,除了core模块,还有众多其它实用模块(均为官方维护),截图展示如下:
3、feign实际使用
基础环境:
SpringCloud 版本 Finchley.RC1
SpringBoot 版本 2.0.1.RELEASE
添加feign依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
启动类:
在启动类中,通过 @EnableDiscoveryClient向 consul 注册,通过 @EnableFeignClients 注解开启 Feign 的功能。
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrix
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
yml文件:
server:
port: 8382
servlet:
context-path: /gateway
spring:
application:
name: spring-demo-service-feign
# 开启Hystrix保护
feign:
hystrix:
enabled: true
# 结合 Ribbon 的负载均衡策略
spring-demo-service:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule
创建 Feign 接口,使用hystrix进行熔断、降级处理:
@FeignClient(value = "spring-demo-service", fallback = ErrorHystrix.class)
public interface SpringDemoFeignService {
@RequestMapping(value = "port", method = RequestMethod.GET)
String hello();
}
fallback类:
/**
* feign使用hystrix进行熔断、降级处理
*/
@Component
public class ErrorHystrix implements SpringDemoFeignService {
@Override
public String hello() {
return "sorry, it's error!";
}
}
前台调用:
@RestController
public class SpringDemoFeignController {
@Autowired
SpringDemoFeignService springDemoFeignService;
@RequestMapping(value = "hello", method = RequestMethod.GET)
public String port() {
return springDemoFeignService.hello();
}
}
这样子,一个简单的Feign服务就搭建完成,Feign的使用相当简单。
4、feign高级规则
4.1 feign开启Gzip压缩
Spring Cloud Feign支持对请求与响应的压缩,以提高通信效率,在服务消费者配置文件开启压缩支持和压缩文件的类型即可:
feign:
compression:
request: #请求
enabled: true #开启
mime-types: text/xml,application/xml,application/json #开启支持压缩的MIME TYPE
min-request-size: 2048 #配置压缩数据大小的下限
response: #响应
enabled: true #开启响应GZIP压缩
注意:
由于开启GZIP压缩之后,Feign之间的调用数据通过二进制协议进行传输,返回值需要修改为ResponseEntity<byte[]>才可以正常显示,否则会导致服务之间的调用乱码。
示例如下:
@PostMapping("/order/{productId}")
ResponseEntity<byte[]> addCart(@PathVariable("productId") Long productId);
4.2 feign开启日志
feign开启日志有两种方式,一种是使用配置文件,一种是使用java代码。
- 方式一:使用java代码
创建FeignLogConfig类,添加一个LoggerBean:
@Configuration
public class FeignLogConfig {
/**
* 日志level有4个级别
* 1.NONE,不记录任何日志
* 2.BASIC,仅记录请求方法、URL以及响应状态码和执行时间
* 3.HEADRES,除了BASIC以外的还会记录请求和响应的头信息
* 4.FULL,所有
* @return
*/
@Bean
Logger.Level feignLogger(){
return Logger.Level.FULL;
}
}
- 方式二:配置文件
logging:
level:
com.test.demo.service.TestFeignClient: debug
4.3 修改Client相关模块
Feign它提供了feign.Client抽象来发送Http请求,因此使得它拥有良好的扩展性,而恰好Feign的子模块里亦提供了对OkHttp以及Apache HttpClient的整合。
我们知道Feign在默认情况下,它发送Http请求使用的是JDK源生的HttpURLConnection。而在实际生产环境下,直接使用它是100%不可取的,这就需要我们使用更加高效的HC。
使用okhttp,能提高qps,因为okhttp有连接池和超时时间进行调优
- 在服务消费者中,添加feign-okhttp依赖:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
- 在配置文件中,禁用默认的http,启用okhttp
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
okhttp:
enabled: true
hystrix:
enabled: true
- 创建OkHttpConfig类,添加okhttp的bean
/**
* 配置okhttp与连接池
* ConnectionPool默认创建5个线程,保持5分钟长连接
*/
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class OkHttpConfig {
@Bean
public okhttp3.OkHttpClient okHttpClient(){
return new okhttp3.OkHttpClient.Builder()
//设置连接超时
.connectTimeout(10 , TimeUnit.SECONDS)
//设置读超时
.readTimeout(10 , TimeUnit.SECONDS)
//设置写超时
.writeTimeout(10 , TimeUnit.SECONDS)
//是否自动重连
.retryOnConnectionFailure(true)
.connectionPool(new ConnectionPool(10 , 5L, TimeUnit.MINUTES))
.build();
}
}
4.4 feign超时设置
# feign启用hystrix,才能熔断、降级
feign.hystrix.enabled=true
# hystrix的超时时间
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
# ribbon的超时时间
ribbon.ReadTimeout=10000
ribbon.ConnectTimeout=10000
4.5 Feign自定义处理返回的异常
这里贴上GitHub上openFeign的wiki给出的自定义errorDecoder例子:
public class StashErrorDecoder implements ErrorDecoder {
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() <= 499) {
//这里是给出的自定义异常
return new StashClientException(
response.status(),
response.reason()
);
}
if (response.status() >= 500 && response.status() <= 599) {
//这里是给出的自定义异常
return new StashServerException(
response.status(),
response.reason()
);
}
//这里是其他状态码处理方法
return errorStatus(methodKey, response);
}
}
4.6 Feign 的GET的多参数传递
目前,feign不支持GET请求直接传递POJO对象的,目前解决方法如下:
- 把POJO拆散城一个一个单独的属性放在方法参数中
- 把方法参数编程Map传递
- 使用GET传递@RequestBody,但此方式违反restful风格
介绍一个最佳实践,通过feign的拦截器来实现:
@Component
@Slf4j
public class FeignCustomRequestInteceptor implements RequestInterceptor {
@Autowired
private ObjectMapper objectMapper;
@Override
public void apply(RequestTemplate template) {
if (HttpMethod.GET.toString() == template.method() && template.body() != null) {
//feign 不支持GET方法传输POJO 转换成json,再换成query
try {
Map<String, Collection<String>> map = objectMapper.readValue(template.bodyTemplate(), new TypeReference<Map<String, Collection<String>>>() {
});
template.body(null);
template.queries(map);
} catch (IOException e) {
log.error("cause exception", e);
}
}
}