AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

快速入門 | 輕松掌握Hystrix實現資源隔離保護系統穩定

來源: 責編: 時間:2023-11-09 09:14:57 323觀看
導讀先看下如下圖,兩個服務之間的調用 A服務調用另外一個B服務。圖片在這個圖當中有個接口A需要調用另外一個服務的接口B。這里看似沒有什么問題。例如,本身A服務接口執行邏輯需要5ms執行完后再調用B服務接口的,調用B接口執

先看下如下圖,兩個服務之間的調用 A服務調用另外一個B服務。hWK28資訊網——每日最新資訊28at.com

圖片圖片hWK28資訊網——每日最新資訊28at.com

hWK28資訊網——每日最新資訊28at.com

在這個圖當中有個接口A需要調用另外一個服務的接口B。這里看似沒有什么問題。hWK28資訊網——每日最新資訊28at.com

例如,本身A服務接口執行邏輯需要5ms執行完后再調用B服務接口的,調用B接口執行完成需要4s,比如下面的下定單扣庫存的流程:hWK28資訊網——每日最新資訊28at.com

圖片圖片hWK28資訊網——每日最新資訊28at.com

hWK28資訊網——每日最新資訊28at.com

這里整個接口調用鏈執行完成需要實際T=4s+5ms;hWK28資訊網——每日最新資訊28at.com

當有大量的請求調用時我們的所有線程都會被阻塞T的時間。本身Tomcat線程池的線程數量是有限的,這就會造成很多的客戶端只能等待,尤其是越是后來的請求等待的時間會越長,同時由于這一個接口把所有的tomcat線程全部占用完,導致了其他的所有服務不可用全部處于等待狀態,從而會拖垮整個tomcat,而這種現象我們稱誒雪崩效應。hWK28資訊網——每日最新資訊28at.com

對于服務之間的調用我們也應該能夠設置一個超時時間,不能讓其一直等待下去。當超過了給定的時間后我們也能夠給予用戶一個響應,通過這種方式來避免這種級聯的故障。如上所述,當整個A服務不可用的時候 這時候的B服務也就不可用了,這種現象被稱為雪崩效應。hWK28資訊網——每日最新資訊28at.com

雪崩效應常見場景

  • 硬件故障:如服務器宕機,機房斷電,光纖被挖斷等。
  • 流量激增:如異常流量,重試加大流量等。
  • 緩存穿透:一般發生在應用重啟,所有緩存失效時,以及短時間內大量緩存失效時。大量的緩存不命中,使請求直擊后端服務,造成服務提供者超負荷運行,引起服務不可用。
  • 程序BUG:如程序邏輯導致內存泄漏,JVM長時間FullGC等。
  • 同步等待:服務間采用同步調用模式,同步等待造成的資源耗盡。

雪崩效應應對策略

針對造成雪崩效應的不同場景,可以使用不同的應對策略,沒有一種通用所有場景的策略,參考如下:hWK28資訊網——每日最新資訊28at.com

  • 硬件故障:多機房容災、異地多活等。
  • 流量激增:服務自動擴容、流量控制(限流、關閉重試)等。
  • 緩存穿透:緩存預加載、緩存異步加載等。
  • 程序BUG:修改程序bug、及時釋放資源等。
  • 同步等待:資源隔離、MQ解耦、不可用服務調用快速失敗等。資源隔離通常指不同服務調用采用不同的線程池;不可用服務調用快速失敗一般通過熔斷器模式結合超時機制實現。

在程序中我們能通過Hystrix來實現資源的隔離,保護我們的服務,不至于導致整個tomcat服務不可用。hWK28資訊網——每日最新資訊28at.com

Hystrix是Netflix開源的一款針對分布式系統的延遲和容錯庫,目的是用來隔離分布式服務故障。它提供線程和信號量隔離,以減少不同服務之間資源競爭帶來的相互影響;提供優雅降級機制;提供熔斷機制使得服務可以快速失敗,而不是一直阻塞等待服務響應,并能從中快速恢復。Hystrix通過這些機制來阻止級聯失敗并保證系統彈性、可用。通過下圖來理解:hWK28資訊網——每日最新資訊28at.com

圖片圖片hWK28資訊網——每日最新資訊28at.com

也就是在調用B服務接口的時候我們放到另外的一個線程中去執行,防止出現上面說的問題。hWK28資訊網——每日最新資訊28at.com

接下來我們來通過程序代碼來看看如何使用hystrix。hWK28資訊網——每日最新資訊28at.com

這里我們以調用訂單服務為例hWK28資訊網——每日最新資訊28at.com

pom.xml加入依賴

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

方式1:

通過繼承HystrixCommandhWK28資訊網——每日最新資訊28at.com

public class OrdersCommand extends HystrixCommand<Orders> {  private RestTemplate restTemplate ;  private Long id ;  public OrdersCommand(RestTemplate restTemplate, Long id) {    super(buildSetter()) ;    this.restTemplate = restTemplate ;    this.id = id ;  }  private static Setter buildSetter() {    comflix.hystrix.HystrixThreadPoolProperties.Setter threadPoolProp = comflix.hystrix.HystrixThreadPoolProperties.Setter() ;    threadPoolProp.withCoreSize(5)      .withKeepAliveTimeMinutes(5)      .withMaxQueueSize(Integer.MAX_VALUE)      .withQueueSizeRejectionThreshold(1000) ;    comflix.hystrix.HystrixCommandProperties.Setter commandProp = comflix.hystrix.HystrixCommandProperties.Setter() ;    commandProp.withCircuitBreakerEnabled(true)      .withExecutionTimeoutInMilliseconds(6000)      .withRequestCacheEnabled(true)      .withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD);    return Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("orders"))           .andCommandKey(HystrixCommandKey.Factory.asKey("getOrder"))           .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("order-pool"))           .andThreadPoolPropertiesDefaults(threadPoolProp)           .andCommandPropertiesDefaults(commandProp) ;  }  @Override  protected Orders run() throws Exception {    return restTemplate.getForObject("http://localhost:9810/orders/queryOrder/{1}", Orders.class, id);  }  @Override  protected Orders getFallback() {    return new Orders() ;  }  @Override  protected String getCacheKey() {    return "order-" + this.id ;  }}

這里我們實現了父類的getFallback方法hWK28資訊網——每日最新資訊28at.com

該方法為當服務調用失敗或者超時會被調用。hWK28資訊網——每日最新資訊28at.com

這里通過buildSetter方法來構建hystrix相關的配置。說明:hWK28資訊網——每日最新資訊28at.com

threadPoolProp.withCoreSize(5)      .withKeepAliveTimeMinutes(5)      .withMaxQueueSize(Integer.MAX_VALUE)      .withQueueSizeRejectionThreshold(1000) ;

以上是對線程池的配置。hWK28資訊網——每日最新資訊28at.com

其它設置:

RequestVolumeThreshold

HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(int)表示在滑動窗口中,至少有多少個請求,才可能觸發斷路。Hystrix 經過斷路器的流量超過了一定的閾值,才有可能觸發斷路。比如說,要求在 10s 內經過斷路器的流量必須達到 20 個,而實際經過斷路器的流量才 10 個,那么根本不會去判斷要不要斷路。hWK28資訊網——每日最新資訊28at.com

ErrorThresholdPercentage

HystrixCommandProperties.Setter().withCircuitBreakerErrorThresholdPercentage(int)表示異常比例達到多少,才會觸發斷路,默認值是 50(%)。如果斷路器統計到的異常調用的占比超過了一定的閾值,比如說在 10s 內,經過斷路器的流量達到了 30 個,同時其中異常訪問的數量也達到了一定的比例,比如 60% 的請求都是異常(報錯 / 超時 / reject),就會開啟斷路。hWK28資訊網——每日最新資訊28at.com

SleepWindowInMilliseconds

HystrixCommandProperties.Setter().withCircuitBreakerSleepWindowInMilliseconds(int)斷路開啟,也就是由 close 轉換到 open 狀態(close -> open)。那么之后在 SleepWindowInMilliseconds 時間內,所有經過該斷路器的請求全部都會被斷路,不調用后端服務,直接走 fallback 降級機制。而在該參數時間過后,斷路器會變為 half-open 半開閉狀態,嘗試讓一條請求經過斷路器,看能不能正常調用。如果調用成功了,那么就自動恢復,斷路器轉為 close 狀態。hWK28資訊網——每日最新資訊28at.com

EnabledHystrixCommandProperties.Setter().withCircuitBreakerEnabled(boolean)控制是否允許斷路器工作,包括跟蹤依賴服務調用的健康狀況,以及對異常情況過多時是否允許觸發斷路。默認值是 true。hWK28資訊網——每日最新資訊28at.com

ForceOpen

HystrixCommandProperties.Setter().withCircuitBreakerForceOpen(boolean)如果設置為 true 的話,直接強迫打開斷路器,相當于是手動斷路了,手動降級,默認值是 false。hWK28資訊網——每日最新資訊28at.com

ForceClosedHystrixCommandProperties.Setter().withCircuitBreakerForceClosed(boolean)hWK28資訊網——每日最新資訊28at.com

如果設置為 true,直接強迫關閉斷路器,相當于手動停止斷路了,手動升級,默認值是 false。hWK28資訊網——每日最新資訊28at.com

參考:hWK28資訊網——每日最新資訊28at.com

圖片圖片hWK28資訊網——每日最新資訊28at.com

comflix.hystrix.HystrixCommandProperties.Setter commandProp = comflix.hystrix.HystrixCommandProperties.Setter() ;    commandProp.withCircuitBreakerEnabled(true)      .withExecutionTimeoutInMilliseconds(6000)      .withRequestCacheEnabled(true)      .withExecutionIsolationStrategy(ExecutionIsolationStrategy.THREAD);

以上是對命令屬性的配置。hWK28資訊網——每日最新資訊28at.com

withCircuitBreakerEnabled:控制是否允許斷路器工作,包括跟蹤依賴服務調用的健康狀況,以及對異常情況過多時是否允許觸發斷路。默認值是 true。hWK28資訊網——每日最新資訊28at.com

withExecutionTimeoutInMilliseconds:執行超時時間的設置。如果一個 command 運行時間超過了設定的時長,那么就被認為是 timeout,然后 Hystrix command 標識為 timeout,同時執行 fallback 降級邏輯。hWK28資訊網——每日最新資訊28at.com

withExecutionIsolationStrategy:執行隔離的策略,這里設置為線程。還可以設置為基于信號量的hWK28資訊網——每日最新資訊28at.com

ExecutionIsolationStrategy.SEMAPHORE:一般如果并發量比較大的情況下我們用信號量,性能要好。如果并發量大你還用線程池,那么你該創建多少的線程呢?而過多的線程帶來了更多線程的切換而影響性能。hWK28資訊網——每日最新資訊28at.com

return Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("orders"))   .andCommandKey(HystrixCommandKey.Factory.asKey("getOrder"))   .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("order-pool"))   .andThreadPoolPropertiesDefaults(threadPoolProp)   .andCommandPropertiesDefaults(commandProp) ;

withGroupKey:服務分組;比如這里調用訂單系統就是一個服務分組。模塊;hWK28資訊網——每日最新資訊28at.com

andCommandKey:服務標識;比如這里訂單系統有一個獲取訂單信息服務。子模塊;hWK28資訊網——每日最新資訊28at.com

andThreadPoolKey:線程池名稱;hWK28資訊網——每日最新資訊28at.com

andThreadPoolPropertiesDefaults:線程池配置;hWK28資訊網——每日最新資訊28at.com

andCommandPropertiesDefaults:命令屬性配置;hWK28資訊網——每日最新資訊28at.com

示例:hWK28資訊網——每日最新資訊28at.com

@GetMapping("/custom/{id}")public Object custom(@PathVariable Long id) {  HystrixRequestContext ctx = HystrixRequestContext.initializeContext() ;  try {    OrdersCommand command = new OrdersCommand(restTemplate, id) ;    System.out.println(Thread.currentThread().getName() + ": " + System.currentTimeMillis()) ;    Orders res = command.execute() ;  } finally {    ctx.shutdown() ;  }  return null ;}

注意:HystrixRequestContext ctx =HystrixRequestContext.initializeContext() ;這行代碼必須調用。hWK28資訊網——每日最新資訊28at.com

方式2:

通過注解的方式。hWK28資訊網——每日最新資訊28at.com

@Servicepublic class RemoteHystrixService {  @Resource  private RestTemplate restTemplate ;  /**   *  <p>   *    groupKey: 服務分組;比如這里調用訂單系統就是一個服務分組。模塊   *    commandKey: 服務標識;比如這里訂單系統有一個獲取訂單信息服務。子模塊   *    threadPoolKey: 線程池名稱;   *    threadPoolProperties:線程池配置   *  </p>   * @author 爺爺   * @param id   * @return Orders   */  @HystrixCommand(fallbackMethod = "defaultOrder",       groupKey = "orders",       commandKey = "getOrder",      threadPoolKey = "order-pool",      threadPoolProperties = {          @HystrixProperty(name = "coreSize", value = "10"),          @HystrixProperty(name = "keepAliveTimeMinutes", value = "5"),          @HystrixProperty(name = "maxQueueSize", value = "1000000"),          @HystrixProperty(name = "queueSizeRejectionThreshold", value = "1000")      },      commandProperties = {          @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),          @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "6000")      }    )  public Orders getOrder(Long id) {    System.out.println(Thread.currentThread() + ", start") ;    Orders res = restTemplate.getForObject("http://localhost:9810/orders/queryOrder/{1}", Orders.class, id);    System.out.println(Thread.currentThread() + ", end") ;    return res ;  }  public Orders defaultOrder(Long id) {    return new Orders() ;  }}

這里具體注解屬性的說明與方式1中 一一對應。hWK28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-17895-0.html快速入門 | 輕松掌握Hystrix實現資源隔離保護系統穩定

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: DDD 與 CQRS 才是黃金組合,你覺得呢?

下一篇: 兩種基于時間窗口的限流器的簡單實現

標簽:
  • 熱門焦點
Top