Resilience4j使用

介绍

Resilience4j是一款轻量级、易用、容错框架,专为 Java 8 和函数式编程而设计。

 

容错是指系统在部分组件(一个或多个)发生故障时仍能正常运作的能力。要具有这个能力,通常要包含断路器(CircuitBreaker)、并发调用隔离(Bulkhead)、限流(RateLimiter)、重试(Retry)、超时(Timeout)机制。

 

超时(Timeout)机制

    @Bulkhead(name = BACKEND_A, type = Bulkhead.Type.THREADPOOL)
    @TimeLimiter(name = BACKEND_A)
    @CircuitBreaker(name = BACKEND_A, fallbackMethod = "futureFallback")
    public CompletableFuture<String> fluxTimeout2() {

        Random random = new Random();
        int sleepTime = random.nextInt(5000);

        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException ie) {
            throw new RuntimeException(ie);
        }

        return CompletableFuture.completedFuture("Hello World from backend A");
    }

    private CompletableFuture<String> futureFallback(TimeoutException ex) {
        return CompletableFuture.completedFuture("Recovered specific TimeoutException: " + ex.toString());
    } 

 

设置超时时间3s,application.properties

resilience4j.timelimiter.configs.default.cancel-running-future=false
resilience4j.timelimiter.configs.default.timeout-duration=3s
resilience4j.timelimiter.instances.backendA.base-config=default 

发起请求

http://127.0.0.1:8072/futureTimeout

    @GetMapping("futureTimeout")
    public String futureTimeout() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        String flux = businessAService.fluxTimeout2().get();
        long endTime = System.currentTimeMillis();
        log.info("-------futureTimeout, "+(endTime - start)+"ms");
        return flux+" "+(endTime - start)+"ms";
    }

  

-------futureTimeout, 682ms
-------futureTimeout, 3010ms  //超时
-------futureTimeout, 1138ms

  

重试(Retry) 

    @GetMapping("/getInvoice")
    @Retry(name = "getInvoiceRetry", fallbackMethod = "getInvoiceFallback")
    public String getInvoice() {
        log.info("getInvoice() call starts here");
        ResponseEntity<String> entity= restTemplate.getForEntity("http://127.0.0.1:8071/world", String.class);
        log.info("Response :" + entity.getStatusCode());
        return entity.getBody();
    }

    public String getInvoiceFallback(Exception e) {
        log.info("---RESPONSE FROM FALLBACK METHOD---");
        return "SERVICE IS DOWN, PLEASE TRY AFTER SOMETIME !!!";
    }

  发起请求

http://127.0.0.1:8072/getInvoice

[2021-12-03 16:40:45,823] [http-nio-8072-exec-3] [INFO] -  c.f.s.c.RetryController 36 getInvoice() call starts here 
[2021-12-03 16:40:46,360] [http-nio-8072-exec-3] [INFO] -  c.f.s.c.RetryController 36 getInvoice() call starts here 
[2021-12-03 16:40:46,872] [http-nio-8072-exec-3] [INFO] -  c.f.s.c.RetryController 36 getInvoice() call starts here //重试3次
[2021-12-03 16:40:46,886] [http-nio-8072-exec-3] [INFO] -  c.f.s.c.RetryController 43 ---RESPONSE FROM FALLBACK METHOD--- 

  

 

posted on 2021-12-03 16:32  rabbit-xf  阅读(645)  评论(0)    收藏  举报