天天看點

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熔斷器

3. 在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的逾時時間。