1. pom.xml에 추가
<!--resilience4j-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
2. 기본 서킷 브레이커 빈 받아서 아래처럼 간편하게 사용
CircuitBreakerFactory circuitBreakerFactory;
@Autowired
public UserServiceImpl(UserRepository userRepository,
BCryptPasswordEncoder passwordEncoder,
Environment env,
RestTemplate restTemplate,
OrderServiceClient orderServiceClient,
CircuitBreakerFactory circuitBreakerFactory) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.env = env;
this.restTemplate = restTemplate;
this.orderServiceClient = orderServiceClient;
this.circuitBreakerFactory = circuitBreakerFactory;
}
/* ErrorDecoder */
//List<ResponseOrder> orderList = orderServiceClient.getOrders(userId);
CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker");
List<ResponseOrder> orderList = circuitBreaker.run(()->orderServiceClient.getOrders(userId),
throwable -> new ArrayList());
---------------------
위쪽까지 사용하면 default 값 circuitBreaker 구현된 것 주입받아서 사용함.
아래쪽 처럼 custom하게 Resilience4JConfig 설정정보 만들면 아래 설정정보로 Bean 만들어서 위 default 설정 코드에서 변경 없이 자동으로 주입 됨.
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
@Configuration
public class Resilience4JConfig {
@Bean
public Customizer<Resilience4JCircuitBreakerFactory> globalCustomConfiguration(){
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.failureRateThreshold(4)
.waitDurationInOpenState(Duration.ofMillis(1000))
.slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
.slidingWindowSize(2)
.build();
TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(4))
.build();
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.timeLimiterConfig(timeLimiterConfig)
.circuitBreakerConfig(circuitBreakerConfig)
.build()
);
}
}
'MSA > MSA관련기술' 카테고리의 다른 글
마이크로미터 (0) | 2022.12.08 |
---|---|
micro service 분산 추적 zipkin (0) | 2022.12.08 |
CircuitBreaker(서킷 브레이커)와 Resilience4J (0) | 2022.12.06 |
kafka 데이터 동기화 방법, connect (0) | 2022.12.04 |
kafka 설치 & 환경구성 (0) | 2022.12.02 |
댓글