什么是hystrix:当高并发访问服务的时候,服务器不能及时的做出响应,hystrix提供服务降级、熔断的功能。
服务降价:
1.生产者服务降级:
pom文件:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
yml文件不需要做另外的添加
启动类加@EnableCircuitBreaker注解
服务层方法:
@HystrixCommand(fallbackMethod = "erroHanderler",commandProperties = {
@HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
public String erro(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Thread.currentThread().getName()+":no this is not ok ";
}
public String erroHanderler(){
return Thread.currentThread().getName()+"服务器繁忙,青稍后点击重试";
}
2.消费者服务降级:
yml添加配置:
feign:
hystrix:
enabled: true
启动类添加@EnableHystrix注解
控制层添加:
@GetMapping("/consume/hytrix/timeout")
@HystrixCommand(fallbackMethod = "erroHanderler",commandProperties = {
@HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value = "1500")
})
public String erro(){
return pymentService.erro();
}
public String erroHanderler(){
return Thread.currentThread().getName()+"llll服务端的服务器繁忙,青稍后点击重试";
}
3.全局的服务降级:由于每一个方法都得对应一个降级的方法导致了代码的拥余,这里设置全局的降级方式。
@RestController
@Slf4j
//设置全局的服务降级
@DefaultProperties(defaultFallback = "erroHanderler")
public class ConsumeController {
@Autowired
consumeService pymentService;
@GetMapping("/consume/hytrix/ok")
public String ok(){
return pymentService.ok();
}
@GetMapping("/consume/hytrix/timeout")
// @HystrixCommand(fallbackMethod = "erroHanderler",commandProperties = {
//// @HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value = "1500")
//// })
@HystrixCommand
public String erro(){
return pymentService.erro();
}
public String erroHanderler(){
return Thread.currentThread().getName()+"llll服务端的服务器繁忙,青稍后点击重试";
}
}
4.为了保证代码的低耦合,可以将降级的代码单独的在实现类中完成。
在接口上面添加falbak参数如果需要降级处理直接调用实现类中对应的方法。
@FeignClient(value = "SPRING-CLOUD-PAYMENT",fallback = consumeServiceImpl.class)
5.熔断:当出现错误的时候采用服务降级,当错误达到一定比例的时候打开熔断器,再次调用没有错误的时候不会恢复,只有达到一定比例的时候就会恢复。
// 服务熔断方法配置
@GetMapping("/consume/curict/erro/{id}")
@HystrixCommand(fallbackMethod = "curictErroHanderler",commandProperties = {
@HystrixProperty(name ="circuitBreaker.enabled",value = "true"),//是否开启熔断器
@HystrixProperty(name ="circuitBreaker.requestVolumeThreshold",value = "10"),//需要请求多少次
@HystrixProperty(name ="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间间隔
@HystrixProperty(name ="circuitBreaker.errorThresholdPercentage",value = "50")//错误率达到多少开启熔断
})
public String curict(@PathVariable("id") Integer id){
if (id<0){
throw new RuntimeException("不能为负数");
}else {
String randId = IdUtil.simpleUUID();
return "调用成功,流水号为:"+randId;
}
}
public String curictErroHanderler(@PathVariable("id") Integer id){
return "this is your 熔断 erro";
}
}
网友评论