如何在调用方法上使用resilience4j?

How to use resilience4j on calling method?

我尝试使用 spring 重试熔断并重试如下,它按预期工作,但问题是无法将 "maxAttempts/openTimeout/resetTimeout" 配置为环境变量(错误应该是常量)。我的问题是如何使用resilience4j来达到下面的要求?

还请建议有一种方法可以将环境变量传递给 "maxAttempts/openTimeout/resetTimeout"。

@CircuitBreaker(value = {
        MongoServerException.class,
        MongoSocketException.class,
        MongoTimeoutException.class
        MongoSocketOpenException.class},
        maxAttempts =  2,
        openTimeout = 20000L ,
        resetTimeout = 30000L)
public void insertDocument(ConsumerRecord<Long, GenericRecord> consumerRecord){

        retryTemplate.execute(args0 -> {
            LOGGER.info(String.format("Inserting record with key -----> %s", consumerRecord.key().toString()));
            BasicDBObject dbObject = BasicDBObject.parse(consumerRecord.value().toString());
            dbObject.put("_id", consumerRecord.key());
            mongoCollection.replaceOne(<<BasicDBObject with id>>, getReplaceOptions());
            return null;
        });

}

@Recover
public void recover(RuntimeException t) {
    LOGGER.info(" Recovering from Circuit Breaker ");
}

使用的依赖项是

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
    </dependency>

您使用的不是resilience4j,而是spring-retry。 你应该调整你的问题的标题。

CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
    .waitDurationInOpenState(Duration.ofMillis(20000))
    .build();
CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("mongoDB");

RetryConfig retryConfig = RetryConfig.custom().maxAttempts(3)
    .retryExceptions(MongoServerException.class,
        MongoSocketException.class,
        MongoTimeoutException.class
        MongoSocketOpenException.class)
    .ignoreExceptions(CircuitBreakerOpenException.class).build();
Retry retry = Retry.of("helloBackend", retryConfig);

Runnable decoratedRunnable = Decorators.ofRunnable(() -> insertDocument(ConsumerRecord<Long, GenericRecord> consumerRecord))
.withCircuitBreaker(circuitBreaker)
.withRetry(retry)
.decorate();

String result = Try.runRunnable(decoratedRunnable )
                .recover(exception -> ...).get();