当服务性能下降时,避免连累其他服务的可用性,此时可以采用降级策略。
1. 引入依赖
org.springframework.cloud spring-cloud-starter-hystrix
Edgware.RELEASE
2. 开启熔断@EnableHystrix
@SpringBootApplication
@EnableHystrix
public class HystrixappApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixappApplication.class, args);
}
}
3. 使用注解,定义降级方法
@RequestMapping(value="/")
@HystrixCommand(fallbackMethod="fallback_hello", commandProperties={
@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1000")
})
public String hello() throws InterruptedException {
Thread.sleep(3000);
return "Welcome Hystrix";
}
// 降级方法
private String fallback_hello() {
return "Request fails. It takes long time to response";
}
此处刻意睡眠3秒钟造成超时场景,会自动调用fallback_hello方法进行降级处理
@HystrixCommand是降级注解,这里定义了fallbackMethod即降级方法,当服务不可用时,会调用降级方法。
commandProperties是降级的一个属性,使用@HystrixProperty定义了一个属性,即超时时间,name是execution.isolation.thread.timeoutInMilliseconds, 值为1000毫秒,即1秒。



