Spring
Spring - Resilience4j circuit breaker example
codeManager
2024. 1. 9. 22:20
반응형
Resilience4j는 내결함성(fault tolerance) 라이브러리다.
Netflix Hystrix는 더이상 개발되지 않아 Resilience4j 사용을 권장하고 있습니다.
Resilience4j는 다음과 같은 모듈을 제공합니다.
- circuitbreaker
- ratelimiter
- bulkhead
- retry
- timelimiter
- cache
CircuitBreaker Config
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreaker circuitBreaker() {
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(50) // Threshold for opening the circuit
.waitDurationInOpenState(Duration.ofMillis(1000)) // Time the circuit will stay open before resetting
.build();
return CircuitBreaker.of("myCircuitBreaker", circuitBreakerConfig);
}
}
- failureRateThreshold: 실패율 임계값(백분율)
- waitDurationInOpenState: circuitbreaker가 OPEN에서 HALF_OPEN으로 전환하기 전 대기 시간
호출 예제
import org.springframework.stereotype.Service;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
@Service
public class MyService {
@CircuitBreaker(name = "customCircuitBreaker", fallbackMethod = "callFallback")
public String riskyServiceCall() {
// Code that might fail or take too long
// For example, an external API call
return "Service Response";
}
public String callFallback(Throwable t) {
// This method is called if riskyServiceCall fails
return "Fallback Response";
}
}
build.gradle 파일
plugins {
id 'org.springframework.boot' version '2.6.3' // Replace with your Spring Boot version
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11' // Replace with your Java version
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
// Resilience4j dependency for Spring Boot
implementation 'io.github.resilience4j:resilience4j-spring-boot2:1.7.1' // Replace with the latest version
// If you need additional Resilience4j modules, add them here. For example:
// implementation 'io.github.resilience4j:resilience4j-circuitbreaker:1.7.1'
// implementation 'io.github.resilience4j:resilience4j-ratelimiter:1.7.1'
// implementation 'io.github.resilience4j:resilience4j-bulkhead:1.7.1'
// implementation 'io.github.resilience4j:resilience4j-retry:1.7.1'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
반응형