Resilience4j系列 - 使用Resilience4j-circuitbreaker优雅实现服务降级

Maven集成

<!-- resilience4j -->
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-circuitbreaker</artifactId>
    <version>1.7.0</version>
</dependency>
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.0</version>
</dependency>
<!-- resilience spring boot integration with annotation requires spring aop -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

通过注解@CircuitBreaker实现

在配置文件里增加circuitbreaker配置信息:

resilience4j:
  circuitbreaker:
    configs:
      default:
        ringBufferSizeInClosedState: 1 # 熔断器关闭时的缓冲区大小
        ringBufferSizeInHalfOpenState: 1 # 熔断器半开时的缓冲区大小
        waitDurationInOpenState: 60000 # 熔断器从打开到半开需要的时间
        failureRateThreshold: 100 # 熔断器打开的失败阈值
        eventConsumerBufferSize: 5 # 事件缓冲区大小
        registerHealthIndicator: true # 健康监测
        automaticTransitionFromOpenToHalfOpenEnabled: true # 是否自动从打开到半开,不需要触发
    instances:
      backendA:
        baseConfig: default
        waitDurationInOpenState: 60000
        failureRateThreshold: 100

为需要实现服务降级的方法增加@CircuitBreaker注解

@Component
public class CircuitBreakCheckedService {

    @CircuitBreaker(name="backendA", fallbackMethod="fallback")
    public boolean checkedMethod(int someInput){
        //写一些会抛出异常的代码。
        return true;
    }

    //该方法的返回类型必须和注解的方法的返回类型一样。
    //该方法的名字必须和fallbackMethod的值一样。
    public boolean fallback(Throwable t){
        return false;
    }

    //如果抛出的异常时CallNotPermittedException。那么这个方法会被执行。
    public boolean fallback(CallNotPermittedException t){
        return false;
    }

    //fallback方法也可以带和注解方法一样的入参。
    public boolean fallback(int someInput, Throwable t){
        return false;
    }
}

通过编程方式实现

//1.创建circuitbreaker配置
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
    .failureRateThreshold(100) //窗口中触发断路器的失败率
    .waitDurationInOpenState(Duration.ofMillis(60000)) //从断开到半开的时间
    .ringBufferSizeInClosedState(3) //断路器未断开时,统计样本的窗口大小
    .permittedNumberOfCallsInHalfOpenState(2) //断路器半开时,允许通过的请求数量
    .automaticTransitionFromOpenToHalfOpenEnabled(true) //是否自动将断路器从断开切换到半开状态
    .build();

//2.创建CircuitBreaker对象
CircuitBreaker circuitBreaker = CircuitBreaker.of("myCircuitBreaker", circuitBreakerConfig);

//3.利用circuitBreaker包装需要进行服务熔断的代码
CheckedFunction0<Boolean> function = CircuitBreaker.decorateCheckedSupplier(
                circuitBreaker, () -> {
        //...
        //把需要控制的方法写在这里。
        //这是一些会抛出异常的代码。
        //...
});

//4.使用Try来执行该包装后的方法。
Try
    .of(f)
    .recover(throwable -> {
    //被控制的方法抛出任何异常之后的处理逻辑
    })
    .recover(CallNotPermittedException.class, e -> {
    //这是特别针对某个特定异常的处理逻辑,只有最精确匹配的异常处理逻辑会被执行
    })
    .get();

如果断路器断开了,那么每次运行时都会触发CallNotPermittedException。可以针对这个异常进行处理,比如提示“服务暂时不可用”之类的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Resilience4j-cache 是一个基于 Resilience4j 的缓存库,提供了对缓存的重试、熔断和限流等功能。它可以很方便地与 Spring Boot 集成使用。 以下是使用 Resilience4j-cache 的步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-cache</artifactId> <version>1.7.0</version> </dependency> ``` 2. 配置缓存 在 Spring Boot 的配置文件中添加以下配置: ``` resilience4j.cache.caffeine.instances.myCache.maximum-size=1000 resilience4j.cache.caffeine.instances.myCache.expire-after-write=5s ``` 该配置表示创建一个名为 `myCache` 的缓存,最大容量为 1000,写入后 5 秒过期。 3. 创建缓存 在代码中创建缓存实例: ``` Cache<String, String> cache = Cache.of("myCache", CacheConfig .custom() .expireAfterWrite(Duration.ofSeconds(5)) .maximumSize(1000) .build() ); ``` 4. 使用缓存 使用 `cache.get(key, loader)` 方法获取缓存项,如果缓存不存在,则会调用 `loader` 方法加载数据。 ``` String value = cache.get("key", () -> { // 从数据库或其他地方加载数据 return "value"; }); ``` 5. 配置重试、熔断和限流 可以使用 Resilience4j 提供的 `Retry`、`CircuitBreaker` 和 `RateLimiter` 等组件对缓存进行重试、熔断和限流等操作。 例如,使用 `Retry` 组件对缓存进行重试操作: ``` Cache<String, String> cache = Cache.of("myCache", CacheConfig .custom() .expireAfterWrite(Duration.ofSeconds(5)) .maximumSize(1000) .build() ); Retry retry = Retry.ofDefaults("retry"); Function<String, String> decorated = Retry.decorateFunction(retry, cache::get); String value = decorated.apply("key"); ``` 以上就是使用 Resilience4j-cache 的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值