在Feign 接口中定义了依赖服务的接口,当Feign调用依赖服务的接口失败时怎么办?
我们也可以在Feign中利用Hystrix的功能,当Feign 调用依赖服务的接口失败时,通过Hystrix调用指定的方法,Spring Cloud默认为Feign整合了Hystrix,但在Spring Cloud 基于Spring boot 2.x的版本中,默认是Feign是关闭Hystrix的。
那么Feign与Hystrix怎么配合使用呢?
1、创建项目futurecloud-feign-hystrix
注意:不需要添加依赖spring-cloud-starter-netflix-hystrix,Spring Cloud默认已为Feign整合了Hystrix。spring boot 主函数也不需要添加注解@EnableCircuitBreaker 来开启Hystrix。主函数类如下:
package com.futurecloud.feignhystrix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient //声明为eureka 客户端
@EnableFeignClients //启动Feign
public class FuturecloudFeignHystrixApplication
{
@Bean //相当于xml中的bean标签,主要是用于调用当前方法获取到指定对象
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main( String[] args )
{
SpringApplication.run(FuturecloudFeignHystrixApplication.class,args);
}
}
开启Hystrix在application.yml中配置