溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot使用斷路器的方法

發(fā)布時間:2020-07-02 17:52:35 來源:億速云 閱讀:513 作者:元一 欄目:編程語言

本篇文章給大家分享的是有關Spring Boot使用斷路器的方法,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

前言

Netflix創(chuàng)建了一個名為hystrix的庫來實現(xiàn)斷路器模式。在微服務體系結構中,有多層服務調(diào)用是常見的。

在微服務架構中,根據(jù)業(yè)務來拆分成一個個的服務,服務與服務之間可以相互調(diào)用(RPC),在Spring Cloud可以用RestTemplate+Ribbon和Feign來調(diào)用。為了保證其高可用,單個服務通常會集群部署。由于網(wǎng)絡原因或者自身的原因,服務并不能保證100%可用,如果單個服務出現(xiàn)問題,調(diào)用這個服務就會出現(xiàn)線程阻塞,此時若有大量的請求涌入,Servlet容器的線程資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統(tǒng)造成災難性的嚴重后果,這就是服務故障的“雪崩”效應。為了解決這個問題,業(yè)界提出了斷路器模型。

斷路器本身是電路上的一種過載保護裝置,當線路中有電器發(fā)生短路時,它能夠及時的切斷故障電路以防止嚴重后果發(fā)生。通過服務熔斷(也可以稱為斷路)、降級、限流(隔離)、異步RPC等手段控制依賴服務的延遲與失敗,防止整個服務雪崩。一個斷路器可以裝飾并且檢測了一個受保護的功能調(diào)用。根據(jù)當前的狀態(tài)決定調(diào)用時被執(zhí)行還是回退。通常情況下,一個斷路器實現(xiàn)三種類型的狀態(tài):open、half-open以及closed:

  • closed狀態(tài)的調(diào)用被執(zhí)行,事務度量被存儲,這些度量是實現(xiàn)一個健康策略所必備的。
  • 倘若系統(tǒng)健康狀況變差,斷路器就處在open狀態(tài)。此種狀態(tài)下,所有調(diào)用會被立即回退并且不會產(chǎn)生新的調(diào)用。open狀態(tài)的目的是給服務器端回復和處理問題的時間。
  • 一旦斷路器進入一個open狀態(tài),超時計時器開始計時。如果計時器超時,斷路器切換到half-open狀態(tài)。在half-open狀態(tài)調(diào)用間歇性執(zhí)行以確定問題是否已解決。如果解決,狀態(tài)切換回closed狀態(tài)。

Spring Boot使用斷路器的方法

斷路器背后的基本思想非常簡單。將受保護的函數(shù)調(diào)用包裝在斷路器對象中,該對象監(jiān)視故障。一旦故障達到某個閾值,斷路器就會跳閘,并且所有對斷路器的進一步調(diào)用都會返回錯誤,而根本不會進行受保護的呼叫。通常,如果斷路器跳閘,您還需要某種監(jiān)控器警報。

Spring Boot使用斷路器的方法

如何快速使用Hystrix呢?

1、加入@EnableCircuitBreaker注解

@EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClientspublic class DroolsAppApplication {
 public static void main(String[] args) {
  SpringApplication.run(DroolsAppApplication.class, args);
 }
}

Hystrix整體執(zhí)行過程,首先,Command會調(diào)用run方法,如果run方法超時或者拋出異常,且啟用了降級處理,則調(diào)用getFallback方法進行降級;

Spring Boot使用斷路器的方法 

2、使用@HystrixCommand注解

@HystrixCommand(fallbackMethod = "reliable")
 public String readingList() {
  for (int i = 0; i < 10; i++) {
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
  return "jinpingmei";
 }

 public String reliable() {
  return "you love interesting book";
 }

3、添加引用

 compile("org.springframework.cloud:spring-cloud-starter-hystrix")
 compile('org.springframework.cloud:spring-cloud-starter-turbine')

4、設置超時時間

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

執(zhí)行結果如下:

Spring Boot使用斷路器的方法 

正常應該返回:

Spring Boot使用斷路器的方法 

你不要喜歡jinpingmei,要喜歡有意思的書;這樣使用好舒服啊,@EnableCircuitBreaker這個注解就這么強大嗎?

HystrixCommandAspect 通過AOP攔截所有的@HystrixCommand注解的方法,從而使得@HystrixCommand能夠集成到Spring boot中,

HystrixCommandAspect的關鍵代碼如下:

1.方法 hystrixCommandAnnotationPointcut() 定義攔截注解HystrixCommand

 2.方法 hystrixCollapserAnnotationPointcut()定義攔截注解HystrixCollapser

 3.方法methodsAnnotatedWithHystrixCommand(…)通過@Around(…)攔截所有HystrixCommand和HystrixCollapser注解的方法。詳細見方法注解

@Aspect
public class HystrixCommandAspect {

 private static final Map<HystrixPointcutType, MetaHolderFactory> META_HOLDER_FACTORY_MAP;

 static {
  META_HOLDER_FACTORY_MAP = ImmutableMap.<HystrixPointcutType, MetaHolderFactory>builder()
    .put(HystrixPointcutType.COMMAND, new CommandMetaHolderFactory())
    .put(HystrixPointcutType.COLLAPSER, new CollapserMetaHolderFactory())
    .build();
 }

 @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")

 public void hystrixCommandAnnotationPointcut() {
 }

 @Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser)")
 public void hystrixCollapserAnnotationPointcut() {
 }

 @Around("hystrixCommandAnnotationPointcut() || hystrixCollapserAnnotationPointcut()")
 public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
  Method method = getMethodFromTarget(joinPoint);
  Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
  if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {
   throw new IllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser " +
     "annotations at the same time");
  }
  MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get(HystrixPointcutType.of(method));
  MetaHolder metaHolder = metaHolderFactory.create(joinPoint);
  HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);
  ExecutionType executionType = metaHolder.isCollapserAnnotationPresent() &#63;
    metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();
  Object result;
  try {
   result = CommandExecutor.execute(invokable, executionType, metaHolder);
  } catch (HystrixBadRequestException e) {
   throw e.getCause();
  }
  return result;
 }

那么HystrixCommandAspect是如何初始化,是通過HystrixCircuitBreakerConfiguration實現(xiàn)的

@Configuration
public class HystrixCircuitBreakerConfiguration {

@Bean
public HystrixCommandAspect hystrixCommandAspect() {
return new HystrixCommandAspect();
}

那么誰來觸發(fā)HystrixCircuitBreakerConfiguration執(zhí)行初始化

先看spring-cloud-netflix-core**.jar包的spring.factories里有這段配置,是由注解EnableCircuitBreaker觸發(fā)

org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\
org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration

那么@EnableCircuitBreaker如何觸發(fā)HystrixCircuitBreakerConfiguration

通過源碼查看,此類通過@Import初始化EnableCircuitBreakerImportSelector類

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(EnableCircuitBreakerImportSelector.class)
public @interface EnableCircuitBreaker {
}

EnableCircuitBreakerImportSelector是SpringFactoryImportSelector子類。此類在初始化后,會執(zhí)行selectImports(AnnotationMetadata metadata)的方法。此方法會根據(jù)注解啟動的注解(這里指@EnableCircuitBreaker)從spring.factories文件中獲取其配置需要初始化@Configuration類(這里是org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerConfiguration),從而最終初始化HystrixCommandAspect 類,從而實現(xiàn)攔截HystrixCommand的功能

以上就是Spring Boot使用斷路器的方法,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI