Feign 简介

是什么

Feign是一个声明式的Web Service客户端,整合了Spring Cloud RibbonSpring Cloud Hystrix

为什么要使用

  • 只需创建一个接口并用注解的方式来配置它,即可完成服务提供方的接口绑定
  • 在使用过程中与Spring Mvc完美衔接
  • 整合了Spring Cloud Ribbon,可实现负载均衡,实现服务高可用
  • 整合了Spring Cloud Hystrix,可实现服务断路及服务降级

简单例子

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>

PersonService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* name 为服务提供者 application-name,fallback 指定服务接口的断路器实现方法,自带Ribbon负债均衡及重试机制
* @author songshuiyang
* @date 2018/10/22 21:53
*/
@FeignClient(name = "eureka-provider", fallback = PersonHystrixFallback.class)
public interface PersonService {

@RequestMapping("getPersonName")
String getPersonName();

@RequestMapping("getPerson")
Person getPerson();

}

PersonHystrixFallback.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Hystrix服务降级 每一个服务接口的断路器实现就是实现类中重写函数的实现
* @author songshuiyang
* @date 2018/10/22 22:26
*/
@Component
public class PersonHystrixFallback implements PersonService {

@Override
public String getPersonName() {
return "HystrixFallbackService ERROR";
}

@Override
public Person getPerson() {
return new Person(0,"HystrixFallbackService ERROR",88);
}
}

FeignAppliacation.java

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @author songshuiyang
* @date 2018/10/22 21:50
*/
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignAppliacation {
public static void main(String[] args) {
SpringApplication.run(FeignAppliacation.class,args);
}
}

application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server:
port: 9031
spring:
application:
name: feign-consumer
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:9010/eureka/,http://localhost:9011/eureka/
ribbon:
ConnectTimeout: 500
ReadTimeout: 5000
feign:
hystrix:
enabled: true