Spring Boot 我可以为resilience4j实现一个自己的装饰器来优化速率限制吗?

ghg1uchk  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(178)

我想优化 * resilience 4j * 速率限制器,以允许

  • 速率限制按用户
    *交错速率限制(例如1个呼叫/秒,但只有30个呼叫/分钟,但只有1000个呼叫/小时)。

这样可以保护资源免受DOS攻击,但不会限制“普通”用户。
是否可以使用默认的resilience 4j装饰器来实现这一点,或者我可以编写自己的装饰器吗?
(Or我用这种方法来抵御DOS攻击是完全错误吗?)

xzv2uavs

xzv2uavs1#

您可以像a fixed issue提到的那样使用.andThen(secondDecorator)

protected <T> Function<Publisher<T>, Publisher<T>> decorateWithCircuitBreakerForSpecificEndpoint() {
    final CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
        .failureRateThreshold(100)
        .recordFailure(throwable -> throwable instanceof RuntimeException)
        .ringBufferSizeInClosedState(10)
        .ringBufferSizeInHalfOpenState(10)
        .waitDurationInOpenState(Duration.ofSeconds(5_000))
        .build();
    final CircuitBreaker circuitBreaker = this.circuitBreakerRegistry.circuitBreaker("test1", circuitBreakerConfig);
    return CircuitBreakerOperator.<T>of(circuitBreaker).andThen(decorateWithCircuitBreakerForSpecificHost());
}

protected <T> Function<Publisher<T>, Publisher<T>> decorateWithCircuitBreakerForSpecificHost() {
    final CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
        .failureRateThreshold(10)
        .recordFailure(throwable -> throwable instanceof RuntimeException)
        .ringBufferSizeInClosedState(5)
        .ringBufferSizeInHalfOpenState(5)
        .waitDurationInOpenState(Duration.ofSeconds(5_000))
        .build();
    final CircuitBreaker circuitBreaker = this.circuitBreakerRegistry.circuitBreaker("test2", circuitBreakerConfig);
    return CircuitBreakerOperator.<T>of(circuitBreaker);
}

相关问题