Hystrix
1、线程隔离
2、服务降级
当服务提供方出错、或处理超时时给出友好的提示
2.1 服务提供方实现服务降级
- 添加pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、引导类添加注解
@EnableEurekaClient //该注解 在新版本中可以省略
@SpringBootApplication
@EnableCircuitBreaker
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class,args);
}
}
3、为方法指定降级方法
@GetMapping("/findOne/{id}")
@HystrixCommand(fallbackMethod ="findOne_fallback",commandProperties =指定超时时间 )
public Goods findOne(@PathVariable("id") int id){
//TimeUnit.MICROSECONDS.sleep(750);
try {
Thread.sleep(2000); //调用service==>dao===>select * from employee
} catch (InterruptedException e) {
e.printStackTrace();
}
Goods goods = goodsService.findOne(id);
return goods;
}
public Goods findOne_fallback(int id){
return null;
}
2.2 调用方实现服务降级
由于调用方采用的是Feign,feign自动集成了hystrix,所以不用添加hystrix的座标
1.实现feign接口开发降级处理类
@Component
public class GoodFeignFallBack implements GoodsFeignClient{
@Override
public Goods findOne(int id) {
return null;
}
}
2、在feign接口上接定降级处理类
@FeignClient(name="eureka-provider",fallback = GoodFeignFallBack.class)
public interface GoodsFeignClient {
@GetMapping("/goods/findOne/{id}")
public Goods findOne(@PathVariable("id") int id);
}
3、在yml中启用hystrix功能
feign:
hystrix:
enabled: true
3、熔断
默认情况下hystrix的断路器是关闭的,此时能够正常访问服务提供方。如果在访问服务提供方时出现大量错误(阀值:5秒中出错20次,5秒中有一半的请求出错)此时断器就会打开,断路器打开之后就不能访问服务提供方。但是过5秒种之后这个断路器又会自动转换为半开状态,此时允许少量的请求过来,如果请求成功次数达预定的阀值。此时断路器又自动被关闭,请求又恢复正常