1、在POM文件添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2、在Spring boot入口类添加注解:
@EnableFeignClients
3、创建一个客户端接口,该接口的方法使用Spring MVC注解绑定提供实际服务的接口,使用@FeignClient注解指定服务名绑定服务:
@FeignClient("hello-service")
public interface HelloClient {
@GetMapping("/hello")
public String hello();
@PostMapping("/hello/{who}")
public String helloWho(@PathVariable("who") String who);
}
4、为服务添加超时和重试功能,hello-service为注册的服务名,如果不加服务名前缀,则是全局设置:
hello-service.ribbon.ConnectTimeout=500
hello-service.ribbon.ReadTimeout=2000
hello-service.ribbon.OkToRetryOnAllOperations=true
hello-service.ribbon.MaxAutoRetriesNextServer=1
hello-service.ribbon.MaxAutoRetries=0
5、使用Hystrix对服务做容错保护,首先需要开启Feign中的Hystrix开关:
feign.hystrix.enabled=true
6、在Spring Boot入口类添加启用断路器的注解:
@EnableCircuitBreaker
设置Hystrix的全局超时时间,到达该超时时间会引起熔断,所以需要这个超时时间大于Ribbon的超时时间,不然Hystrix先超时了,Ribbon的重试机制无法起到效果:
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
6、使用Hystrix实现服务降级,首先先需要定义一个服务降级类,来实现前面HelloClient的方法:
@Component
public class HelloClientFallback implements HelloClient {
@Override
public String hello() {
return "error";
}
@Override
public String helloWho(String who) {
return "error";
}
}
之后,在服务绑定接口HelloClient中,通过@FeignClient注解的fallback属性来指定对应的服务降级实现类,原来的注解改成以下形式:
@FeignClient(name = "hello-service", fallback = HelloClientFallback.class)
7、可能遇到的问题:
① Method xxx not annotated with HTTP method type (ex. GET, POST)
原因:在老版本的Feign使用中,不能使用@GetMapping("/xxx")方式声明。Dalston版本已支持。
解决办法:改成@RequestMapping(value = "/xxx", method = RequestMethod.GET)。
② PathVariable annotation was empty on param 0.
原因:未在@PathVariable注解中指定value。
解决办法:指定@PathVariable注解的value,例如@PathVariable(“id”)。