Feign概述
Feign是一种声明式、模块化的HTTP客户端。在Spring Cloud项目使用Feign,使其HTTP访问远程服务,就像调用本地的方法一样。可以无感知的调用远程服务。
- 可插拔的注解支持,包括Feign注解和JAX-RS注解。
- 支持可插拔的HTTP编码器和解码器
- 支持Hystrix和它的Fallback。
- 支持Ribbon的负载均衡,结合注册中心一起使用。
- 支持HTTP请求和响应的压缩。
- 支持替换不同HTTP组件。okhttp3,
所有配置查看类
spring-cloud-openfeign-core-2.2.9.RELEASE.jar下/META-INF/spring-configuration-metadata.json
简单示例
引入库
<dependencies>
<!--服务注册中心客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--远程HTTP调用组件-->
<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>
</dependencies>
示例代码
启动类
@SpringBootApplication
@EnableDiscoveryClient
#用于扫描当前类包下,所有FeignClient
@EnableFeignClients
public class ShopApp {
public static void main(String... args){
new SpringApplication(ShopApp.class).run(args);
}
}
编写Feign
FeignClient参数说明
在调用:fallback的时候需要开启feign.hystrix.enabled=true
否则无效,不会开启熔断回调。
- name: 指定FeignClient名称,如果采用了服务注册于发现,则是
微服务名称
- url: 指定的地址
- decode404: 当发生404异常时,如果为ture,会调用decoder进行解码,否则抛出FeignException
- configuration: Feign配置类
- fallback: 当调用发生异常时候,对调用对应类中的方法
- fallbackFactory:工厂类,通用异常错误处理逻辑。
- path:定义路径的统一前缀
@FeignClient(name = "customer", path = "/customer/",fallback = CustomerFallbackService.class, primary = false)
public interface CustomerService {
@RequestMapping(method = RequestMethod.GET, value = "/test")
String test();
}
/**
* 需要开启:feign.hystrix.enabled=true
* 这是在回调失败时候,会自动调用下列方法
* 其中不包含负载均衡失败的调用
*/
class CustomerFallbackService implements CustomerService{
public String test(){
return "error test";
}
}
Controller调用
@RestController
@RequestMapping("shop")
public class ShopController {
@Autowired
private CustomerService customerService;
@GetMapping("test")
public String test(){
return "shop test";
}
@GetMapping("customer")
public String customer(){
return customerService.test();
}
}
替换为Okhttp
okhttp功能和特性
- 支持SPDY,可以合并多个到同一个主机的请求。
- 使用连接池技术减少请求的延迟(如果SPDY是可用的)。
- 使用GZIP压缩减少传输的数据量
- 缓存响应避免重复的网络请求。
引入库
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
配置yml
feign:
okhttp:
enabled: true #开启okhttp,作为请求组件
httpclient:
enabled: false #httpclient默认是开启的,所以需要关闭
替换为httpclient5
引入库
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.3</version>
</dependency>
配置yml
feign:
httpclient:
enabled: false #httpclient默认是开启的,所以需要关闭
hc5:
enabled: true #开启http5,作为请求组件