|
| 1 | +package cn.iocoder.springcloud.labx24.resilience4jdemo.controller; |
| 2 | + |
| 3 | +import io.github.resilience4j.bulkhead.annotation.Bulkhead; |
| 4 | +import io.github.resilience4j.timelimiter.annotation.TimeLimiter; |
| 5 | +import org.slf4j.Logger; |
| 6 | +import org.slf4j.LoggerFactory; |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; |
| 8 | +import org.springframework.stereotype.Service; |
| 9 | +import org.springframework.web.bind.annotation.GetMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 11 | +import org.springframework.web.bind.annotation.RequestParam; |
| 12 | +import org.springframework.web.bind.annotation.RestController; |
| 13 | + |
| 14 | +import java.util.concurrent.CompletableFuture; |
| 15 | +import java.util.concurrent.ExecutionException; |
| 16 | + |
| 17 | +@RestController |
| 18 | +@RequestMapping("/time-limiter-demo") |
| 19 | +public class TimeLimiterDemoController { |
| 20 | + |
| 21 | + @Autowired |
| 22 | + private TimeLimiterService timeLimiterService; |
| 23 | + |
| 24 | + @GetMapping("/get_user") |
| 25 | + public String getUser(@RequestParam("id") Integer id) throws ExecutionException, InterruptedException { |
| 26 | + return timeLimiterService.getUser0(id).get(); |
| 27 | + } |
| 28 | + |
| 29 | + @Service |
| 30 | + public static class TimeLimiterService { |
| 31 | + |
| 32 | + private Logger logger = LoggerFactory.getLogger(TimeLimiterService.class); |
| 33 | + |
| 34 | + @Bulkhead(name = "backendD", type = Bulkhead.Type.THREADPOOL) |
| 35 | + @TimeLimiter(name = "backendF", fallbackMethod = "getUserFallback") |
| 36 | + public CompletableFuture<String> getUser0(Integer id) throws InterruptedException { |
| 37 | + logger.info("[getUser][id({})]", id); |
| 38 | + Thread.sleep(10 * 1000L); // sleep 10 秒 |
| 39 | + return CompletableFuture.completedFuture("User:" + id); |
| 40 | + } |
| 41 | + |
| 42 | + public CompletableFuture<String> getUserFallback(Integer id, Throwable throwable) { |
| 43 | + logger.info("[getUserFallback][id({}) exception({})]", id, throwable.getClass().getSimpleName()); |
| 44 | + return CompletableFuture.completedFuture("mock:User:" + id); |
| 45 | + } |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | +} |
0 commit comments