1.pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2.配置文件
#开启feign
feign.hystrix.enabled=true
#断路器,断路器跳闸后等待多长时间重试
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=1000
#断路器,请求发出后多长时间超时
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000
3.启动类加上注解@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class EurekaHystrixApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(
EurekaHystrixApplication.class)
.web(true).run(args);
}
}
4.Service类
说明fallback与fallbackFactory区别,fallback只是出错运行你指定的方法,拿不到错误信息,fallbackFactory可以拿到错误信息
@FeignClient(name="eureka-hystrix",fallbackFactory=HelloFallbackFactory.class)
public interface HelloService {
@RequestMapping(value="/test",method=RequestMethod.GET)
String hiService(@RequestParam("name") String name);
@RequestMapping(value="/test1",method=RequestMethod.GET)
String hiService1(@RequestParam("name") String name);
}
5.接口
public interface HelloFallback extends HelloService{
}
6.HelloFallbackFactory,注意添加注解@Component
@Component
public class HelloFallbackFactory implements FallbackFactory<HelloService>{
@Override
public HelloService create(Throwable e) {
System.out.println("错误信息:"+e.getMessage());
return new HelloFallback() {
@Override
public String hiService(String name) {
return "error";
}
@Override
public String hiService1(String name) {
return "error1";
}
};
}
}