简介
Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单。它的使用方法是定义一个服务接口然后在上面添加注解。
 Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。
一句话:定义微服务的接口,加入Feign相关注解就能实现微服务之间的调用。
使用
- 加入依赖:
 
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
 
- 在主启动类上加入@EnableFeignClients
 - 定义服务接口
这里表明getPaymentById会调用"CLOUD-PAYMENT-SERVICE"服务上的"/payment/get/{id}"接口。
等价于之前的http://CLOUD-PAYMENT-SERVICE/payment/get/id 
@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);//与服务方controller中方法名保持一致
}
 
注意:@PathVariable 中一定要写"id",因为feign向前兼容JDK1.5之前需要写。
- controller层注入调用
 
	@Resource
    private PaymentFeignService paymentFeignService;
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable Long id){
        return paymentFeignService.getPaymentById(id);
    }
 
特性
内置ribbon提供负载均衡
 超时控制,消费断1s内没有接收到响应则报错。
 日志增强。
设置超时时间:
application.yml
feign:
  client:
    config:
      default:
        connect-timeout: 5000
        read-timeout: 5000
 
日志增强:
配置类:
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feiginLoggerLever(){
        return Logger.Level.FULL;
    }
}
 
在application.yml中添加日志需要记录的接口:
logging:
  level:
    org.example.springcloud.service.PaymentFeignService: debug
 
再次运行,调用接口时会出现下面的日志情况。
 



















