[17.0.0.3 以及更新版本]

改良 Liberty 中的微服務復原力

您可以使用「MicroProfile 容錯」特性,讓服務的呼叫更具復原力。這項特性是「Eclipse MicroProfile 容錯規格 1.0」的實作。此特性使用 Failsafe 開放程式碼庫來提供一個程式設計模型,以透過各種型樣來支援具復原力的微服務,這些型樣包括:重試、斷路器、隔板、逾時和備用。

開始之前

如需「MicroProfile 容錯」特性實作之開放程式碼 MicroProfile 規格的相關資訊,請參閱 Eclipse MicroProfile 容錯規格 1.0

程序

  1. mpFaultTolerance-1.0 特性新增至 server.xml 檔中的 featureManager 元素。
    <featureManager>
       <feature>mpFaultTolerance-1.0</feature>
    </featureManager>
  2. 使用程式碼 Snippet,來改良微服務的復原力。
    容錯斷路器提供一種作法,讓系統快點失敗。它會暫時讓服務無法執行,避免服務讓系統超載。
    「隔板」容錯用來限制對某服務的並行呼叫數。隔板會限制服務呼叫所能使用的系統資源量。程式碼 Snippet 會要求 server.xml 檔中除了指定 mpFaultTolerance-1.0 特性,還需指定 Liberty concurrent-1.0 特性。

    「斷路器」程式碼 Snippet 1:建立配置了 CircuitBreaker 和 Timeout 的 CircuitBreakerBean

    @RequestScoped
    public class CircuitBreakerBean {
    
        private int executionCounterA = 0;
    
        // The combined effect of the specified requestVolumeThreshold and failureRatio is that 3  
        // failures will trigger the circuit to open.
        // After a 1 second delay the Circuit will allow fresh attempts to invoke the service.
        @CircuitBreaker(delay = 1, delayUnit = ChronoUnit.SECONDS, requestVolumeThreshold = 3, failureRatio = 1.0)
        // A service is considered to have timed out after 3 seconds
        @Timeout(value = 3, unit = ChronoUnit.SECONDS)
        public String serviceA() {
            executionCounterA++;
    
            if (executionCounterA <= 3) {
                //Sleep for 10 secs to force a timeout
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println("serviceA interrupted");
                }
            }

    CircuitBreaker 程式碼 Snippet 2:使用 CircuitBreakerBean。

    @Inject
    CircuitBreakerBean bean;
    
    // FaultTolerance bean with circuit breaker, should fail 3 times
    for (int i = 0; i < 3; i++) {
        try {
            bean.serviceA();
            throw new AssertionError("TimeoutException not caught");
        } catch (TimeoutException e) {
                //expected
        }
    }
    
    // The CircuitBreaker should be open, so calling serviceA should generate a 
    // CircuitBreakerOpenException.
    try {
        bean.serviceA();
        throw new AssertionError("CircuitBreakerOpenException not caught");
    } catch (CircuitBreakerOpenException e) {
        //expected
    }
    
    //allow time for the circuit to re-close
    Thread.sleep(3000);
    
    // The CircuitBreaker should be closed and serviceA should now succeed.
    String res = bean.serviceA();
    if (!"serviceA: 4".equals(res)) {
        throw new AssertionError("Bad Result: " + res);
    }

    「備用和重試」程式碼 Snippet 1:配置了 FallbackHandler 和 Retry 原則的 FTServiceBean

    @RequestScoped
    public class FTServiceBean {
    
        // Annotate serviceA with a named FallbackHandler and a Retry policy specifying the
        // number of retries.
        @Retry(maxRetries = 2)
        @Fallback(StringFallbackHandler.class)
        public String serviceA() {
            throw new RuntimeException("Connection failed");
            return null;
        }   
    }

    「備用和重試」程式碼 Snippet 2:FallbackHandler,這是一旦主要服務失敗要驅動的程式碼

    @Dependent
    public class StringFallbackHandler implements FallbackHandler<String> {
    
        @Override
        public String handle(ExecutionContext context) {
            return "fallback for " + context.getMethod().getName();
        }
    }

    「備用和重試」程式碼 Snippet 3:使用 FTServiceBean

    private @Inject FTServiceBean ftServiceBean;
        
    try {
        // Call serviceA, which will be retried twice in the event of failure, after which
        // the FallbackHandler will be driven.
        String result = ftServiceBean.serviceA();
        if(!result.contains("serviceA"))
           throw new AssertionError("The message should be \"fallback for serviceA\"");
     }
    catch(RuntimeException ex) {
        throw new AssertionError("serviceA should not throw a RuntimeException");
    }

    「隔板」程式碼 Snippet 1:建立配置了 Bulkhead 的 BulkheadBean

    @RequestScoped
    @Asynchronous
    public class BulkheadBean {
    
        private final AtomicInteger connectATokens = new AtomicInteger(0);
    
        // Configure a Bulkhead that supports at most 2 concurrent threads.
        @Bulkhead(maxThreads = 2)
        public Future<Boolean> connectA(String data) throws InterruptedException {
            System.out.println("connectA starting " + data);
            int token = connectATokens.incrementAndGet();
            try {
                if (token > 2) {
                    throw new RuntimeException("Too many threads in connectA[" + data + "]: " + token);
                }
                Thread.sleep(5000);
                return CompletableFuture.completedFuture(Boolean.TRUE);
            } finally {
                connectATokens.decrementAndGet();
                System.out.println("connectA complete " + data);
            }
        }
    }

    「隔板」程式碼 Snippet 2:使用 BulkheadBean

    @Inject
    BulkheadBean bean;
    
    // connectA has a poolSize of 2
    // The first two calls to connectA should be run straight away, in parallel, each around
    // 5 seconds
    Future<Boolean> future1 = bean.connectA("One");
    Thread.sleep(100);
    Future<Boolean> future2 = bean.connectA("Two");
    Thread.sleep(100);
    
    // The next two calls to connectA should wait until the first 2 have finished
    Future<Boolean> future3 = bean.connectA("Three");
    Thread.sleep(100);
    Future<Boolean> future4 = bean.connectA("Four");
    Thread.sleep(100);
    
    //total time should be just over 10s
    Thread.sleep(11000);
    
    if (!future1.get(1000, TimeUnit.MILLISECONDS)) {
        throw new AssertionError("Future1 did not complete properly");
    }
    if (!future2.get(1000, TimeUnit.MILLISECONDS)) {
        throw new AssertionError("Future2 did not complete properly");
    }
    if (!future3.get(1000, TimeUnit.MILLISECONDS)) {
        throw new AssertionError("Future3 did not complete properly");
    }
    if (!future4.get(1000, TimeUnit.MILLISECONDS)) {
        throw new AssertionError("Future4 did not complete properly");
    }

指示主題類型的圖示 作業主題

檔名:twlp_microprofile_fault_tolerance.html