导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
RestTemplate整合
-
启动类添加注解@EnableCircuitBreaker
@SpringBootApplication //旧版本 //@EnableCircuitBreaker //新版本 @EnableHystrix public class ClientdemoApplication { public static void main(String[] args) { SpringApplication.run(ClientdemoApplication.class, args); } }
-
使用注解引进调用失败执行的方法
@HystrixCommand(fallbackMethod = "service5Fail") public Object service5() { String url2 = "http://eurekaserve/shello"; ResponseEntity<String> forEntity = restTemplate.getForEntity(url2, String.class); System.out.println(forEntity.getBody()); return "service5: " + forEntity.getBody(); } public Object service5Fail(){ return "service5Fail"; }
Feign整合
开启Hystrix
//旧版本
feign.hystrix.enabled=true
//新版本
feign.circuitbreaker.enabled=true
方式一
实现API接口,重写方法
@Component
public class FeignTestImpl implements FeignTest {
@Override
public String shello() {
return "shello is failed";
}
}
注解配置fallback
@FeignClient(name = "eurekaserve",fallback = FeignTestImpl.class)
public interface FeignTest {
@GetMapping(path = "/shello")
String shello();
}
方式二
实现FallbackFactory接口,重写方法create(Throwable cause)
@Component
public class MyError implements FallbackFactory<FeignTest> {
@Override
public FeignTest create(Throwable cause) {
return new FeignTest() {
@Override
public String shello() {
if (cause instanceof Exception)
return "MyException";
else
return "MyError";
}
};
}
}
注解配置fallback
@FeignClient(name = "eurekaserve" ,fallbackFactory = MyError.class)
public interface FeignTest {
@GetMapping(path = "/shello")
String shello();
}