resilience4j + timelimiter 示例

This commit is contained in:
YunaiV
2020-05-20 19:51:56 +08:00
parent 4cdb91db9c
commit a7212d451f
2 changed files with 56 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
package cn.iocoder.springboot.lab59.resillience4jdemo.controller;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@RestController
@RequestMapping("/time-limiter-demo")
public class TimeLimiterDemoController {
@Autowired
private TimeLimiterService timeLimiterService;
@GetMapping("/get_user")
public String getUser(@RequestParam("id") Integer id) throws ExecutionException, InterruptedException {
return timeLimiterService.getUser0(id).get();
}
@Service
public static class TimeLimiterService {
private Logger logger = LoggerFactory.getLogger(TimeLimiterService.class);
@Bulkhead(name = "backendD", type = Bulkhead.Type.THREADPOOL)
@TimeLimiter(name = "backendF", fallbackMethod = "getUserFallback")
public CompletableFuture<String> getUser0(Integer id) throws InterruptedException {
logger.info("[getUser][id({})]", id);
Thread.sleep(10 * 1000L); // sleep 10 秒
return CompletableFuture.completedFuture("User:" + id);
}
public CompletableFuture<String> getUserFallback(Integer id, Throwable throwable) {
logger.info("[getUserFallback][id({}) exception({})]", id, throwable.getClass().getSimpleName());
return CompletableFuture.completedFuture("mock:User:" + id);
}
}
}

View File

@@ -42,3 +42,10 @@ resilience4j:
wait-duration: 5s # 下次重试的间隔,单位:微秒。默认为 500 毫秒
retry-exceptions: # 需要重试的异常列表。默认为空
ingore-exceptions: # 需要忽略的异常列表。默认为空
# Resilience4j 的超时限制器 TimeLimiter 配置项,对应 TimeLimiterProperties 属性类
timelimiter:
instances:
backendF:
timeout-duration: 1s # 等待超时时间,单位:微秒。默认为 1 秒
cancel-running-future: true # 当等待超时时,是否关闭取消线程。默认为 true