天天看点

hystrix熔断和降级的区别_Hystrix熔断器

1. 熔断的思想介绍

当整个系统的某个条件被触发,就会执行之前设定好的动作,为了保证系统稳定的工作。系统跑在服务器上,要保证N个9的高可用,熔断机制就是一个很好的保证提醒。

hystrix熔断和降级的区别_Hystrix熔断器

2. Hystrix在Ribbon中的实现

步骤一:引入依赖

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
           

步骤二:在启动类上使用注解开启Hystrix

@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
public class QfSpringCloudNetflixEurekaConsumerRibbonApplication
           

步骤三:在要进行熔点的客户端方法上设置熔断方法

@HystrixCommand(fallbackMethod = "hiError")
public String sayHi(String message){
 //调用服务的提供者并获得结果并返回

    //服务提供者返回的是一个String
 String uri = "http://HELLO-SPRING-CLOUD-SERVICE-ADMIN/hi?message="+message;
 return restTemplate.getForObject(uri,String.class);
}

//当熔断被打开,那么此方法会被调用
public String hiError(String message){
 return String.format("您的消息:%s未发送成功,请检查您的网络",message);
}
           

3.熔断的条件是什么?

1)服务宕机

2)服务抛异常

3)服务超时

比如说服务需要睡3秒,但是客户端的ribbon以及hystrix的默认连接超时时间都是1秒,因此需要通过配置将时间修改成指定值(建议3-5秒),这样才不会因为调用服务的时间过长而造成熔断。

#ribbon的全局超时时间的设置
ribbon:
 ReadTimeout: 4000
 ConnectTimeout: 4000

#设置全局方法的超时时间
hystrix:
 command:
 default:
 execution:
 isolation:
 thread:
 timeoutInMilliseconds: 10000

半开
# 设置全局方法的超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds`
# 设置时间滑动窗口(默认值是10秒)
hystrix.command.default.metrics.rollingStats.timeInMilliseconds`
# 当熔断器打开的时候,多长时间内会拒绝所有的请求,直接调用降级方法。过了这个时间,就会进入到半开状态
hystrix.command.default.metrics.rollingStats.sleepWindowInMilliSeconds
           
hystrix熔断和降级的区别_Hystrix熔断器

4. 在Feign中使用Hystrix

步骤一:开启hystrix

Feign已经集成了Hystrix,默认是关闭状态,需要手动开启

feign:
 hystrix:
 enabled: true
           

步骤二:创建要配置熔断的接口的实现类(降级类)

@Component
public class AdminServiceHystrix implements MyService {
 @Override
 public String sayHi(String message) {
 return String.format("您的网络有问题!!!");
    }
}
           

步骤三: 在要配置熔断的接口上使用注解,指明之前配好的降级类

@FeignClient(value = "hello-spring-cloud-service-admin",fallback = AdminServiceHystrix.class)
public interface MyService {

 @RequestMapping("hi")
 public String sayHi(@RequestParam String message);

}
           

Feign中的超时时间怎么计算:

Ribbon的超时时间+hystrix的超时时间。