Spring Cloud Gateway 使用 Resilience4j

之前一篇blog写了在microservice中使用resilience4j,可以实现细粒度的控制,精确到某一个API或者service,但是如果想要实现粗粒度的全局控制,在每一个microservice中进行相同的配置就未免有些负赘悬疣的感觉了. 所以直接在gateway转发的时候添加一个filter,既可以实现全域的控制.

POM

在pom中引入需要的依赖

		<dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-boot2</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
        </dependency>

Configuration

新建一个config类,当然 你也可以直接在application.java中定义bean,但更好的方案是单独定义configguration,避免bean定义过多之后代码看上去十分冗杂.

package xxxx.config;

import java.time.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;

@Configuration
public class Resilience4jConfiguration {

    private final static Logger log = LoggerFactory.getLogger(Resilience4jConfiguration.class);

    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer(CircuitBreakerRegistry circuitBreakerRegistry) {
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
                .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(5)).build()).build());
    }
}

我这里circuitBreaker使用的是默认配置,下面表格可以看到具体有那些配置.配置方式和timeLimiterConfig方式一样.

Config propertyDefault ValueDescription
failureRateThreshold50Configures the failure rate threshold in percentage.

When the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls.
slowCallRateThreshold100Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold

When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls.
slowCallDurationThreshold60000 [ms]Configures the duration threshold above which calls are considered as slow and increase the rate of slow calls.
permittedNumberOfCalls
InHalfOpenState
10Configures the number of permitted calls when the CircuitBreaker is half open.
maxWaitDurationInHalfOpenState0Configures a maximum wait duration which controls the longest amount of time a CircuitBreaker could stay in Half Open state, before it switches to open.
Value 0 means Circuit Breaker would wait infinitely in HalfOpen State until all permitted calls have been completed.
slidingWindowTypeCOUNT_BASEDConfigures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed.
Sliding window can either be count-based or time-based.

If the sliding window is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated.
If the sliding window is TIME_BASED, the calls of the last slidingWindowSize seconds recorded and aggregated.
slidingWindowSize100Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed.
minimumNumberOfCalls100Configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate or slow call rate.
For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated.
If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed.
waitDurationInOpenState60000 [ms]The time that the CircuitBreaker should wait before transitioning from open to half-open.
automaticTransition
FromOpenToHalfOpenEnabled
falseIf set to true it means that the CircuitBreaker will automatically transition from open to half-open state and no call is needed to trigger the transition. A thread is created to monitor all the instances of CircuitBreakers to transition them to HALF_OPEN once waitDurationInOpenState passes. Whereas, if set to false the transition to HALF_OPEN only happens if a call is made, even after waitDurationInOpenState is passed. The advantage here is no thread monitors the state of all CircuitBreakers.
recordExceptionsemptyA list of exceptions that are recorded as a failure and thus increase the failure rate.
Any exception matching or inheriting from one of the list counts as a failure, unless explicitly ignored via ignoreExceptions.
If you specify a list of exceptions, all other exceptions count as a success, unless they are explicitly ignored by ignoreExceptions.
ignoreExceptionsemptyA list of exceptions that are ignored and neither count as a failure nor success.
Any exception matching or inheriting from one of the list will not count as a failure nor success, even if the exceptions is part of recordExceptions.
recordExceptionthrowable -> true

By default all exceptions are recored as failures.
A custom Predicate which evaluates if an exception should be recorded as a failure.
The Predicate must return true if the exception should count as a failure. The Predicate must return false, if the exception
should count as a success, unless the exception is explicitly ignored by ignoreExceptions.
ignoreExceptionthrowable -> false

By default no exception is ignored.
A custom Predicate which evaluates if an exception should be ignored and neither count as a failure nor success.
The Predicate must return true if the exception should be ignored.
The Predicate must return false, if the exception should count as a failure.

下面的表格是关于timerlimiter的配置

Config propertyDefault valueDescription
timeoutDuration5 [s]The default wait time a thread waits for a permission
limitRefreshPeriod500 [ns]The period of a limit refresh. After each period the rate limiter sets its permissions count back to the limitForPeriod value
limitForPeriod50The number of permissions available during one limit refresh period

YML

接下来在yml中配置 default-filters就可以了

cloud:
    gateway:
      routes:
        - id: xxxx
          uri: xxx
          predicates:
            - Path=xxxx
      default-filters:
        - CircuitBreaker 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值