8.11. Hystrix

8.11.1. 개요

Camel 2.18부터 사용 가능합니다.

Hystrix 패턴을 사용하면 애플리케이션이 Camel 경로에서 회로 차단기를 제공할 수 있는 networkshistrix와 통합할 수 있습니다. Hystrix는 대기 시간 및 내결함성 라이브러리입니다.

  • 원격 시스템, 서비스 및 타사 라이브러리에 대한 액세스 지점을 분리
  • 계단식 중지 실패
  • 오류가 발생할 수 있는 복잡한 분산 시스템에서 탄력성 활성화

maven을 사용하는 경우 pom.xml 파일에 다음 종속성을 추가하여 Hystrix를 사용합니다.

<dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-hystrix</artifactId>
      <version>x.x.x</version>
      <!-- Specify the same version as your Camel core version. -->
</dependency>

8.11.2. Java DSL 예

다음은 인라인 대체 경로로 다시 대체하여 느린 작업으로부터 보호하는 Hystrix 엔드포인트를 보여주는 예입니다. 기본적으로 시간 초과 요청은 1000ms 이므로 HTTP 끝점이 성공할 수 있어야 합니다.

from("direct:start")
    .hystrix()
        .to("http://fooservice.com/slow")
    .onFallback()
        .transform().constant("Fallback message")
    .end()
    .to("mock:result");

8.11.3. XML 구성 예

다음은 동일한 예이지만 XML에서는 다음과 같습니다.

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <hystrix>
      <to uri="http://fooservice.com/slow"/>
      <onFallback>
        <transform>
          <constant>Fallback message</constant>
        </transform>
      </onFallback>
    </hystrix>
    <to uri="mock:result"/>
  </route>
</camelContext>

8.11.4. Hystrix 대체 기능 사용

onFallback() 메서드는 메시지를 변환하거나 빈을 호출하거나 폴백으로 다른 것을 호출할 수 있는 로컬 처리를 위한 것입니다. 네트워크를 통해 외부 서비스를 호출해야 하는 경우 첫 번째 명령 개체를 고갈하지 않도록 자체 스레드 풀을 사용하는 독립적인 HystrixCommand 개체에서 실행되는 onFallbackViaNetwork() 메서드를 사용해야 합니다.

8.11.5. Hystrix 구성 예

Hystrix에는 다음 섹션에 나열된 많은 옵션이 있습니다. 아래 예제에서는 상태가 이동될 때 다시 요청을 시도하기 전에 회로 차단기가 5초(기본값)가 아닌 10초 동안 실행 타임아웃을 설정하는 데 필요한 Java DSL을 보여줍니다.

from("direct:start")
    .hystrix()
        .hystrixConfiguration()
             .executionTimeoutInMilliseconds(5000).circuitBreakerSleepWindowInMilliseconds(10000)
        .end()
        .to("http://fooservice.com/slow")
    .onFallback()
        .transform().constant("Fallback message")
    .end()
    .to("mock:result");

다음은 동일한 예이지만 XML에서는 다음과 같습니다.

<camelContext xmlns="http://camel.apache.org/schema/spring">
<camelContext xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:start"/>
    <hystrix>
      <hystrixConfiguration executionTimeoutInMilliseconds="5000" circuitBreakerSleepWindowInMilliseconds="10000"/>
      <to uri="http://fooservice.com/slow"/>
      <onFallback>
        <transform>
          <constant>Fallback message</constant>
        </transform>
      </onFallback>
    </hystrix>
    <to uri="mock:result"/>
  </route>
</camelContext>
 You can also configure Hystrix globally and then refer to that
configuration. For example:
<camelContext xmlns="http://camel.apache.org/schema/spring">
   <!-- This is a shared config that you can refer to from all Hystrix patterns. -->
   <hystrixConfiguration id="sharedConfig" executionTimeoutInMilliseconds="5000" circuitBreakerSleepWindowInMilliseconds="10000"/>

   <route>
         <from uri="direct:start"/>
         <hystrix hystrixConfigurationRef="sharedConfig">
         <to uri="http://fooservice.com/slow"/>
         <onFallback>
            <transform>
               <constant>Fallback message</constant>
            </transform>
         </onFallback>
      </hystrix>
      <to uri="mock:result"/>
   </route>
</camelContext>

8.11.6. 옵션

thshystrix 구성 요소는 다음 옵션을 지원합니다. Hystrix는 기본값을 제공합니다.

이름기본값유형설명

circuitBreakerEnabled

true

부울

회로 차단기가 상태를 추적하고 쇼크 요청을 이동하는 경우 단락 요청을 사용하는지 여부를 결정합니다.

circuitBreakerErrorThresholdPercentage

50

정수

회로가 열린 상태로 이동해야 하는 오류 백분율을 설정하고 폴백 논리에 대한 쇼트 서킷 요청을 시작합니다.

circuitBreakerForceClosed

false

부울

true 값은 회로 차단기가 오류 백분율에 관계없이 요청을 허용하는 closed 상태로 강제 적용합니다.

circuitBreakerForceOpen

false

부울

true 값은 회로 차단기가 모든 요청을 거부하는 열린(트립됨) 상태로 강제 적용합니다.

circuitBreakerRequestVolumeThreshold

20

정수

회로를 이동할 롤링 창에서 최소 요청 수를 설정합니다.

circuitBreakerSleepWindownInMilliseconds

5000

정수

회로를 추적한 후 요청을 거부한 후 시간을 설정합니다. 이 시간이 지나면 회로가 다시 종료되어야 하는지를 요청 시도가 허용됩니다.

commandKey

노드 ID

문자열

Hystrix 명령을 식별합니다. 이 옵션을 구성할 수 없습니다. 이 옵션은 항상 명령을 고유하게 만드는 노드 ID입니다.

corePoolSize

10

정수

코어 thread-pool 크기를 설정합니다. 동시에 실행할 수 있는 HystrixCommand 개체의 최대 수입니다.

executionIsolationSemaphoreMaxConcurrentRequests

10

정수

ExecutionIsolationStrategy.SEMAPHORE.NET Framework를 사용할 때 HystrixCommand.run() 메서드가 수행할 수 있는 최대 요청 수를 설정합니다.

executionIsolationStrategy

스레드

문자열

이러한 격리 전략 중 HystrixCommand.run() 가 를 사용하여 실행되는 것을 나타냅니다. THREAD 는 별도의 스레드에서 실행되며 동시 요청은 thread-pool의 스레드 수에 의해 제한됩니다. 호출 스레드에서 SEMAPHORE 가 실행되고 동시 요청은 세마포어 수에 의해 제한됩니다.

executionIsolationThreadInterruptOnTimeout

true

부울

시간 초과가 발생할 때 HystrixCommand.run() 실행이 중단되어야 하는지 여부를 나타냅니다.

executionTimeoutInMilliseconds

1000

정수

실행 완료를 위해 시간 초과를 밀리초 단위로 설정합니다.

executionTimeoutEnabled

true

부울

HystrixCommand.run() 의 실행이 시간 초과되어야 하는지 여부를 나타냅니다.

fallbackEnabled

true

부울

hy strixCommand.getFallback() 에 대한 호출이 실패 또는 거부될 때 시도되는지 여부를 결정합니다.

fallbackIsolationSemaphoreMaxConcurrentRequests

10

정수

HystrixCommand.getFallback() 메서드가 호출 스레드에서 수행할 수 있는 최대 요청 수를 설정합니다.

groupKey

CamelHystrix

문자열

통계 및 회로 차단기 속성의 상관 관계를 유지하는 데 사용되는 Hystrix 그룹을 식별합니다.

keepAliveTime

1

정수

연결 유지 시간을 분 단위로 설정합니다.

maxQueueSize

-1

정수

BlockingQueue 구현의 최대 큐 크기를 설정합니다.

metricsHealthSnapshotIntervalInMilliseconds

500

정수

상태 스냅샷을 사용하도록 허용하는 사이의 대기 시간(밀리초)을 설정합니다. 상태 스냅샷은 성공 및 오류 백분율을 계산하고 회로 차단기 상태에 영향을 미칩니다.

metricsRollingPercentileBucketSize

100

정수

버킷당 보관되는 최대 실행 횟수를 설정합니다. If more executions occur during the time they will wrap and start over-writing at the beginning of the bucket.

metricsRollingPercentileEnabled

true

부울

실행 대기 시간을 추적해야 하는지 여부를 나타냅니다. 대기 시간은 백분율로 계산됩니다. false 값은 요약 통계(mean, percentiles)가 -1로 반환됩니다.

metricsRollingPercentileWindowBuckets

6

정수

rollingPercentile 창이 분할될 버킷 수를 설정합니다.

metricsRollingPercentileWindowInMilliseconds

60000

정수

밀리초 단위로 백분위 계산을 허용하도록 실행 시간이 유지되는 롤링 창의 기간을 설정합니다.

metricsRollingStatisticalWindowBuckets

10

정수

롤링 통계 창이 분할되는 버킷 수를 설정합니다.

metricsRollingStatisticalWindowInMilliseconds

10000

정수

이 옵션과 다음 옵션은 HystrixCommandHystrixObservableCommand 실행에서 메트릭을 캡처하는 데 적용됩니다.

queueSizeRejectionThreshold

5

정수

큐 크기 거부 임계값 - CryostatmaxQueueSize 에 도달하지 않은 경우에도 거부가 발생하는 인위 최대 큐 크기를 설정합니다.

requestLogEnabled

true

부울

HystrixCommand 실행 및 이벤트를 HystrixRequestLog 에 로깅해야 하는지 여부를 나타냅니다.

threadPoolKey

null

문자열

이 명령을 실행해야 하는 thread-pool을 정의합니다. 기본적으로 이 키는 그룹 키와 동일한 키를 사용합니다.

threadPoolMetricsRollingStatisticalWindowBucket

10

정수

롤링 통계 창이 분할되는 버킷 수를 설정합니다.

threadPoolMetricsRollingStatisticalWindowInMilliseconds

10000

정수

통계 롤링 창의 기간을 밀리초 단위로 설정합니다. 스레드 풀에 대한 메트릭이 유지되는 시간입니다.