SpringCloud整合Hystrix(三)整合Feign
Feign整合Hystrix
回退机制配置
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@ServletComponentScan
//打开Feign的开关
@EnableFeignClients
public class SaleApp {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
new SpringApplicationBuilder(SaleApp.class).web(true).run(args);
}
}
在application.yml里面打开feign整合Hystrix的开关
feign:
hystrix:
enabled: true
断路器配置
application.yml
针对某个方法配置
hystrix:
command:
HelloClient#toHello(): #该方法超过0.5秒,断路器熔断触发回退的方法
execution:
isolation:
thread:
timeoutInMilliseconds: 500
circuitBreaker: #10秒内请求数量超过3次满足熔断第一个条件,如果请求中50%的请求是失败的满足第二个条件
requestVolumeThreshold: 3
针对全局配置
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
circuitBreaker:
requestVolumeThreshold: 3
服务方提供的接口
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "hello";
}
@RequestMapping(value = "/toHello", method = RequestMethod.GET)
public String toHello() throws Exception {
Thread.sleep(1000);
return "timeout hello";
}
调用方接口
@FeignClient(name = "spring-hy-member", fallback = HelloClientFallback.class)
public interface HelloClient {
//Feign翻译器翻译了四个注解:
//@RequestMapping;@RequestParm;@RequestHeader;@PathVariable
@RequestMapping(method = RequestMethod.GET, value = "/hello")
public String hello();
@RequestMapping(method = RequestMethod.GET, value = "/toHello")
public String toHello();
}
回退方法
@Component
public class HelloClientFallback implements HelloClient {
public String hello() {
return "fallback hello";
}
public String toHello() {
return "fallback timeout hello";
}
}
测试调用
@RestController
public class FeignController {
@Autowired
private HelloClient helloClient;
@RequestMapping(method = RequestMethod.GET, value = "/hello")
public String hello() {
return helloClient.hello();
}
//测试断路器
@RequestMapping(method = RequestMethod.GET, value = "/toHello")
public String toHello() {
String result = helloClient.toHello();
HystrixCircuitBreaker breaker = HystrixCircuitBreaker.Factory
.getInstance(HystrixCommandKey.Factory
.asKey("HelloClient#toHello()"));
System.out.println("断路器状态:" + breaker.isOpen());
return result;
}
}
注意:
断路器开启后,短路默认5s 开始尝试是否恢复
参考:https://blog.csdn.net/tongtong_use/article/details/78611225
以上为疯狂SpringCloud微服务架构实战学习笔记
感谢杨恩雄老师:https://my.oschina.net/JavaLaw