Feign是一种声明式、模块化的HTTP客户端。在Spring Cloud项目使用Feign,使其HTTP访问远程服务,就像调用本地的方法一样。可以无感知的调用远程服务。
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);
}
}
FeignClient参数说明
在调用:fallback的时候需要开启feign.hystrix.enabled=true
否则无效,不会开启熔断回调。
微服务名称
@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";
}
}
@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功能和特性
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
feign:
okhttp:
enabled: true #开启okhttp,作为请求组件
httpclient:
enabled: false #httpclient默认是开启的,所以需要关闭
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.3</version>
</dependency>
feign:
httpclient:
enabled: false #httpclient默认是开启的,所以需要关闭
hc5:
enabled: true #开启http5,作为请求组件