Spring Cloud Feign 整合了Spring Cloud Ribbon 与 Spring Cloud Hystrix,除此之外它还提供了一种声明式的Web服务客户端定义方式。 Feign在RestTemplate的基础上对其封装,由它来帮助我们定义和实现依赖服务接口的定义。
快速入门
我们继续使用之前实现的hello-service 服务,这里我们会通过 Spring Cloud Feign 提供的声明式服务绑定功能来实现对该服务接口的调用。
- 创建工程,取名为 feign-consumer,并在pom.xml里面引入spring-cloud-starter-netflix-eureka-serve 和 spring-cloud-starter-feign依赖。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gildata</groupId>
<artifactId>feign-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>feign-consumer</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 创建应用主类FeignConsumerApplication,并用@EnableFeignClients 注解开启 Spring Cloud Feign 的支持功能。
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
- 定义 HelloService 接口,通过@FeignClient 注解指定服务名来绑定服务,然后再使用Spring MVC的注解来绑定具体该服务提供的 REST 接口.
/**
* Created by liaock on 2019/1/8.
*/
@FeignClient("hello-service")
public interface HelloService {
@RequestMapping("/hello")
String hello();
}
- 接着创建一个 ConsumerController 来实现对 Feign 客户端的调用。注入上面定义的 HelloService实例,并在helloConsumer函数中调用这个绑定了 hello-service 服务接口的客户端来向该服务发起 /hello 接口的调用。
/**
* Created by liaock on 2019/1/9.
*/
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
public String HelloConsumer(){
return helloService.hello();
}
}
- 最后,同Ribbon实现的消费者一样配置application.properties
server.port=9001
spring.application.name=feign-consumer
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
测试验证
启动服务注册中心以及两个HELLO-SERVICE,然后启动 FEIGN-CONSUMER
发送几次GET请求到 http://localhost:9001/feign-consumer,可以得到如之前 Ribbon 实现时的效果一样,正确返回了“Hello World”。并且根据控制台的输出,我们可以看到Feign实现的消费者,依然是利用Ribbon维护了针对 HELLO-SERVIEC 的服务列表信息,并且通过轮询实现了客户端负载均衡。而与Ribbon 不同的是,通过Feign我们只需要定义服务绑定接口,以声明式的方法,优雅而简单地实现了服务调用。
参数绑定
在介绍参数绑定前,我们先扩展下 hello-service。 增加如下接口定义。
package com.gildata.springbootdemo.controller;
import com.gildata.springbootdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.apache.log4j.Logger;
import java.util.Random;
/**
* Created by liaock on 2018/12/17.
*/
@RestController
public class HelloController {
private final Logger logger = Logger.getLogger(getClass());
@RequestMapping("/hello")
public String index(){
return "Hello World !";
}
@RequestMapping(value = "hello1", method = RequestMethod.GET)
public String hello(@RequestParam String name){
return "Hello "+ name;
}
@RequestMapping(value = "hello2", method = RequestMethod.GET)
public User hello(@RequestHeader String name, @RequestHeader Integer age){
return new User(name,age);
}
@RequestMapping(value = "hello3", method = RequestMethod.POST)
public String hello(@RequestBody User user){
return "Hello "+ user.getName() + "," + user.getAge();
}
}
定义User对象
package com.gildata.springbootdemo.entity;
/**
* Created by liaock on 2019/1/9.
*/
public class User {
private String name;
private Integer age;
public User(){ }
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
改造 feign-consumer(修改 HelloService以及ConsumerController)
package com.gildata.feignconsumer.service;
import com.gildata.feignconsumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
/**
* Created by liaock on 2019/1/8.
*/
@FeignClient("hello-service")
@Service
public interface HelloService {
@RequestMapping("/hello")
String hello();
@RequestMapping(value = "hello1", method = RequestMethod.GET)
String hello(@RequestParam("name") String name);
@RequestMapping(value = "hello2", method = RequestMethod.GET)
User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
@RequestMapping(value = "hello3", method = RequestMethod.GET)
String hello(@RequestBody User user);
}
package com.gildata.feignconsumer.controller;
import com.gildata.feignconsumer.entity.User;
import com.gildata.feignconsumer.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by liaock on 2019/1/9.
*/
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
@RequestMapping(value = "/feign-consumer",method = RequestMethod.GET)
public String helloConsumer(){
return helloService.hello();
}
@RequestMapping(value = "/feign-consumer2",method = RequestMethod.GET)
public String helloConsumer2(){
StringBuilder sb = new StringBuilder();
sb.append(helloService.hello()).append("\n");
sb.append(helloService.hello("DIDI")).append("\n");
sb.append(helloService.hello("DIDI",30)).append("\n");
sb.append(helloService.hello(new User("DIDI",30))).append("\n");
return sb.toString();
}
}
测试验证:发送请求到 http://localhost:9001/feign-consumer2
得到如下结果:
Hello World ! Hello DIDI User{name='DIDI', age=30} Hello DIDI,30
调用成功 !
继承特性
当使用Spring MVC 的注解来绑定服务接口时,我们几乎可以从服务提供方的Controller 中依靠复制操作,构建出相应的服务客户端绑定接口,可以考虑进一步抽象,我们可以通过Spring Cloud Feign的继承特性来实现REST接口定义的复用.
- 为了能够复用 DTO 与接口定义,我们先创建一个基础的Maven工程,命名为 hello-service-api
- 由于在hello-service-api 中需要定义可同时复用于服务端与客户端的接口,我们要使用到Spring MVC 的注解,所以需要在 pom.xml里面加入 spring-boot-starter-web 依赖,如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gildata</groupId>
<artifactId>hello-service-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hello-service-api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 创建 HelloService 并将上面实现的User复制到 hello-service-api
package com.example.service;
import com.example.entity.User;
import org.springframework.web.bind.annotation.*;
/**
* Created by liaock on 2019/1/9.
*/
@RequestMapping("/refactor")
public interface HelloService {
@RequestMapping(value = "hello4", method = RequestMethod.GET)
String hello(@RequestParam("name") String name);
@RequestMapping(value = "hello5", method = RequestMethod.GET)
User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
@RequestMapping(value = "hello6", method = RequestMethod.POST)
String hello(@RequestBody User user);
}
- 将hello-service-api mvn install 到本地仓库,并在hello-service及feign-consumer中引入,下面对hello-service 以及 feign-consumer 重构
hello-service的修改.
package hello.controller;
/**
* Created by liaock on 2019/1/9.
*/
import com.example.entity.User;
import com.example.service.HelloService;
import org.springframework.web.bind.annotation.*;
@RestController
public class RefactorHelloController implements HelloService {
@Override
@RequestMapping(value = "hello4", method = RequestMethod.GET)
public String hello(@RequestParam("name") String name) {
return "Hello "+ name;
}
@Override
@RequestMapping(value = "hello5", method = RequestMethod.GET)
public User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age) {
return new User(name,age);
}
@Override
@RequestMapping(value = "hello6", method = RequestMethod.POST)
public String hello(@RequestBody User user) {
return "Hello "+user.getName() + "," + user.getAge();
}
}
feign-consumer 的修改
package com.gildata.feignconsumer.service;
import com.example.service.HelloService;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
/**
* Created by liaock on 2019/1/9.
*/
@Service
@FeignClient(value = "HELLO-SERVICE")
public interface RefactorHelloService extends HelloService {
}
package com.gildata.feignconsumer.controller;
import com.example.entity.User;
import com.gildata.feignconsumer.service.HelloService;
import com.gildata.feignconsumer.service.RefactorHelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by liaock on 2019/1/9.
*/
@RestController
public class ConsumerController {
@Autowired
HelloService helloService;
@Autowired
RefactorHelloService refactorHelloService;
@RequestMapping(value = "/feign-consumer",method = RequestMethod.GET)
public String helloConsumer(){
return helloService.hello();
}
@RequestMapping(value = "/feign-consumer2",method = RequestMethod.GET)
public String helloConsumer2(){
StringBuilder sb = new StringBuilder();
sb.append(helloService.hello()).append("\n");
sb.append(helloService.hello("DIDI")).append("\n");
sb.append(helloService.hello("DIDI",30)).append("\n");
sb.append(helloService.hello(new com.gildata.feignconsumer.entity.User("DIDI",30))).append("\n");
return sb.toString();
}
@RequestMapping(value = "/feign-consumer3",method = RequestMethod.GET)
public String helloConsumer3(){
StringBuilder sb = new StringBuilder();
sb.append(refactorHelloService.hello("MIMI")).append("\n");
sb.append(refactorHelloService.hello("MIMI",30)).append("\n");
sb.append(refactorHelloService.hello(new User("MIMI",30))).append("\n");
return sb.toString();
}
}
测试验证
访问 http://localhost:9001/feign-consumer3
提示
Hello MIMI User{name='MIMI', age=30} Hello MIMI,30
测试成功 !
Ribbon 配置
全局配置
可以使用ribbon.=的方式来设置ribbon的各项参数。比如:
ribbon.ConnectTimeOut=500
ribbon.ReadTimeout=5000
指定服务配置
比如:
HELLO-SERVICE.ribbon.ConnectTimeOut=500
HELLO-SERVICE.ribbon.ReadTimeout=2000
重试机制
Hystrix 配置
下面我们将介绍如何在Spring Cloud Feign中配置Hystrix 属性以及如何实现服务降级.
全局配置
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
禁用 Hystrix
feign.hystrix.enabled=false
针对某个客户端关闭 Hystrix ,通过使用 @Scope(“prototype”) 注解为指定的客户端配置 Feign.Builder 实例
构建一个关闭 Hystrix 的配置类
@Configuration
public class DisableHystrixConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder(){
return Feign.builder();
}
}
@FeignClient(value = "SERIVCE-USER",configuration = DisableHystrixConfiguration.class)
@Service
public interface HelloService {
···
}
指定命令配置
采用hystrix.command. 作为前缀。 针对上一节介绍的尝试机制中对/hello接口的熔断超时时间的配置如下:
hystrix.command.hello.execution.isolation.thread.timeoutInMilliseconds=5000
服务降级配置
我们对全面创建的 feign-consumer 工程进行改造。
- 服务降级逻辑的实现需要问Feign客户端的定义接口编写一个具体的接口实现类。 具体如下:
package com.gildata.feignconsumer.service;
import com.gildata.feignconsumer.entity.User;
/**
* Created by liaock on 2019/1/9.
*/
public class HelloServiceFallback implements HelloService {
@Override
public String hello() {
return "error";
}
@Override
public String hello(String name) {
return "error";
}
@Override
public User hello(String name, Integer age) {
return new User("未知",0);
}
@Override
public String hello(User user) {
return "error";
}
}
- 在服务绑定接口的 HelloService 中,通过@FeignClient 注解的fallback 属性来制定对应的服务降级实现类。
package com.gildata.feignconsumer.service;
import com.gildata.feignconsumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
/**
* Created by liaock on 2019/1/8.
*/
@FeignClient(name="hello-service",fallback = HelloServiceFallback.class)
@Service
public interface HelloService {
@RequestMapping("/hello")
String hello();
@RequestMapping(value = "hello1", method = RequestMethod.GET)
String hello(@RequestParam("name") String name);
@RequestMapping(value = "hello2", method = RequestMethod.GET)
User hello(@RequestHeader("name") String name, @RequestHeader("age") Integer age);
@RequestMapping(value = "hello3", method = RequestMethod.GET)
String hello(@RequestBody User user);
}
测试验证
启动服务注册中心和feign-consumer,但是不启动 hello-service 服务,发送get请求到http://localhost:9001/feign-consumer2,该接口会分别调用 HelloService 中的4个绑定接口, 但因为 hello-service 服务没有启动,会直接出发服务降级,输出如下:
error
error
name=未知, age=0
error
测试成功 !