SpringBoot項目集成Hystrix


Hystrix

 

Hystrix是由Netflix開源的一個服務隔離組件,通過服務隔離來避免由於依賴延遲、異常,引起資源耗盡導致系統不可用的解決方案。

 

 

1、什么是服務熔斷

    服務熔斷就是對該服務的調用執行熔斷,對應后續請求,不在繼續調用該目標服務,而是直接返回,從而可以快速釋放資源,

   或者服務出現故障,會把故障信息返回給客戶端。這種犧牲局部,保全整體的措施就叫做熔斷。

 

2、熔斷的意義

 

  本質上是為了保護系統,讓系統保持穩定;

 

  減少性能損耗;

 

  及時響應;

 

  熔斷器的功能:異常處理、日志記錄、測試失敗的操作、手動復位、並發、加速斷路、重試失敗請求。

3、Hystrix的三種狀態

  1.熔斷關閉狀態(Closed)

    服務沒有故障時,熔斷器所處的狀態,對調用方的調用不做任何限制。

  2.熔斷開啟狀態(Open)

    在固定時間窗口內(Hystrix默認是10秒),接口調用出錯比率達到一個閾值(Hystrix默認為50%),會進入熔斷開啟狀態。

    進入熔斷狀態后,后續對該服務接口的調用不再經過網絡,直接執行本地的fallback方法。

  3.半熔斷狀態(Half-Open)

    在進入熔斷開啟狀態一段時間之后(Hystrix默認是5秒),熔斷器會進入半熔斷狀態。所謂半熔斷就是嘗試恢復服務調用,

    允許有限的流量調用該服務,並監控調用成功率。如果成功率達到預期,則說明服務已恢復,進入熔斷關閉狀態;如果成功率仍舊很低,則重新進入熔斷關閉狀態。

三個狀態的轉化關系如下圖:

 

 

 

4、SpringBoot項目集成Hystrix熔斷技術

添加Hystrix依賴  

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

添加yml配置

# Hystrix settings hystrix: command: default: execution: isolation: strategy: THREAD thread: # 線程超時15秒,調用Fallback方法 timeoutInMilliseconds: 15000 metrics: rollingStats: timeInMilliseconds: 15000 circuitBreaker: # 10秒內出現3個以上請求(已臨近閥值),並且出錯率在50%以上,開啟斷路器.斷開服務,調用Fallback方法 requestVolumeThreshold: 3 sleepWindowInMilliseconds: 10000

添加熔斷配置類

package com.lmq.configuration; import com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect; import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 熔斷配置 */ @Configuration public class HystrixConfiguration { @Bean public HystrixCommandAspect hystrixAspect() { return new HystrixCommandAspect(); } @Bean public ServletRegistrationBean getServlet() { HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet(); ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet); registrationBean.setLoadOnStartup(1); registrationBean.addUrlMappings("/actuator/hystrix.stream"); registrationBean.setName("HystrixMetricsStreamServlet"); return registrationBean; } }

至此就算是把Hystrix集成進項目了,下面看具體使用

@RestController
@RequestMapping(value = "/webservice", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@DefaultProperties(defaultFallback = "timeOutError")
public class WebServiceController {

    /**
     * 該方法是對接口調用超時的處理方法
     */
    public String timeOutError() {
        return "time out";
    }

    @GetMapping(value = "test") 
   public String getDate() {
    
return "success";
  }

只需要在Controller層添加@DefaultProperties注解,defaultFallback為服務失敗后默認調用的方法,這里直接返回time out,具體可根據業務需求返回指定數據實現服務降級。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM