1.定义
跟Ribbon一样,Feign也是由Netfix提供的,Feign是一个声明式,模板化的Web Service客户端,它简化了开发者编写Web服务客户端的操作,开发者可以通过简单的接口和注解来调用Http API,Spring Cloud Feign,它整合了Ribbon和Hystrix,具有可拔插,基于注解,负载均衡,服务熔断等一系列便捷功能。
相比较Ribbon+RestTemplate的方式,Feign大大简化了代码的开发,Fegin支持多种注解,包括DFegin注解,JAX-RS注解,Spring MVC注解等,Spring Cloud对Fegin进行了优化,整合了Ribbon和Eureka,
2.Ribbon和Feign的区别
Ribbon是一个通用的HTTP客户端工具,Fegin是基于Ribbon实现的
3.Feign的优点
Feign是声明式的Web Service客户端
支持Fegin注解, Spring Mvc注解,jax_rs注解
Feign基于Ribbon实现,使用起来更加简单
Fegin集成了Hystrix,具备服务熔断的功能
4.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ygdSpringCloud</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>feign</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
</project>
5.application.yml文件
server:
port: 8050
spring:
application:
name: feign
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
feign:
hystrix:
enabled: true
feign.hystrix.enabled: 是否开启熔断器
6.编写feign调用的接口
@FeignClient(value = "provider",fallback = FeignError.class)
public interface FeignProviderClient {
@GetMapping("/student/findAll")
public List<Student> findAll();
@GetMapping("/student/index")
public String index();
}
加上@FeignClient注解,value为服务提供者在注册中心的别名,fallback为降级服务,熔断后处理的类
创建FeginProviderClient接口的实现类FeignError,定义容错处理逻辑,通过@Component注解将实例注入ioc容器
@Component
public class FeignError implements FeignProviderClient{
@Override
public List<Student> findAll() {
return null;
}
@Override
public String index() {
return "服务器维护中";
}
7.调用微服务测试
![](https://i-blog.csdnimg.cn/blog_migrate/f5ba044982d1b03d99287496726c4c4d.png)