一、简介
Feign是一个声明式的Web Service客户端。它的出现使开发Web Service客户端变得很简单。使用Feign只需要创建一个接口加上对应的注解,比如:FeignClient注解。Feign有可插拔的注解,包括Feign注解和JAX-RS注解。Feign也支持编码器和解码器,Spring Cloud Open Feign对Feign进行增强支持Spring MVC注解,可以像Spring Web一样使用HttpMessageConverters等。
Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。
其实在我看来feign和ribbon几乎的区别就在于,ribbon是每次调用的时候去写需要调用的微服务,feign是提前将对应的微服务配置为一个接口去调用。
二、SpringCloud OpenFeign入门案例
一.添加依赖
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
二.主启动类(开启OpenFeign)
在启动程序中使用@EnableFeignClients来enable Feign。
@SpringBootApplication
@EnableFeignClients //开启Feign
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class,args);
}
}
三.Service接口
通过调用指定了具体微服务的接口,去调用该微服务。
@FeignClient(value = “CLOUD-PROVIDER-SERVICE”) //指定调用哪个微服务
@Component
@FeignClient(value = "CLOUD-PROVIDER-SERVICE") //指定调用哪个微服务
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}") //哪个地址
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
四.Controller
Controller去调用Service的接口
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
//openfeign底层ribbon,客户端默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
三.OpenFeign超时控制(默认为一秒钟)
服务双方调用,肯定会有一定的时延,设置最大可以等待的时间,默认为一秒。
#设置feign 客户端超时时间(openFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
四.OpenFeign日志级别
logging:
level:
#feign日志以什么级别监控哪个接口
com.springcloud.service.PaymentFeignService: debug
五.OpenFeign配置负载均衡模式
user-server:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule