Hystrix Spring Boot 환경에서 사용하기

Dev. 로티·2022년 3월 3일
2

Spring boot

목록 보기
9/12
post-thumbnail

저번 포스팅에서 Hystrix가 무엇이고, 다양한 속성들과 간단한 사용방법에 대해 알아보았습니다.

이번 포스팅에서는 Spring Boot환경에서 Hystrix를 어떻게 사용할 수 있는지에 대해 알아보도록 하겠습니다.


Dependancy

가장 먼저 Hystrix를 Spring Boot에서 사용하기 위해서는 dependancy를 추가해주어야합니다.

[ Gradle ]

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

[ Maven ]

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring.cloud-version}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

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

springCloudVersion은 자신이 현재 사용하고 있는 Spring Boot 버전에 따라 다르기 때문에 아래의 표를 참고해주시기 바랍니다.

Release TrainBoot Version
2021.0.x aka Jubilee2.6.x
2020.0.x aka Ilford2.4.x, 2.5.x (Starting with 2020.0.3)
Hoxton2.2.x, 2.3.x (Starting with SR5)
Greenwich2.1.x
Finchley2.0.x
Edgware1.5.x
Dalston1.5.x

Hystrix Configuration

의존성 등록이 끝나셨다면 다음은 @EnableCircuitBreaker 어노테이션을 추가하여 Hystrix를 활성화 시켜야합니다.

예시)

@EnableCircuitBreaker
@Configuration
public class HystrixConfig {
	...
}

Hystrix Command

그 후 자신이 적용하고자 하는 메소드에 @HystrixCommand 어노테이션을 추가하면 해당 메소드 호출시 Hystrix가 관리하게 됩니다.

@Service
public class OrderService {
    ...
	
    @HystrixCommand(fallbackMethod = "placeOrderFallback",
    	commandProperties = {
            ...
    	}
	)
    public Long placeOrder(String orderer, PlaceOrderDto placeOrderDto) {
        
		...
		return order.getId();
    }

    Long placeOrderFallback(String orderer, PlaceOrderDto placeOrderDto){
        return 123L;
    }
}

Hystrix Command Properties 예시

@HystrixCommand(
	groupKey = "groupKey",
    commandKey = "commandKey", 
    threadPoolKey = "threadPoolKey", 
    fallbackMethod = "fallbackTest << [중요! 해당 메소드가 같은 클래스 내에 반드시 있어야함]",
    
    commandProperties = {
  	@HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds", value = "30000"),
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "4"),
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "60000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "180000")
    }, 
    
    threadPoolProperties = {
    @HystrixProperty(name = "coreSize", value = "30"),
    @HystrixProperty(name = "maxQueueSize", value = "101"),
    @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15")}
    )

더 자세한 Hystrix Properties 정보를 보고싶으시다면 저번 포스팅을 참고해주세요.

0개의 댓글