4.3.3. 创建容错应用程序

创建容错应用,实现容错模式的重试、超时和回退模式。

先决条件

  • 已配置了 Maven 依赖项。

流程

  1. 创建用于存储类文件的目录:

    $ mkdir -p APPLICATION_ROOT/src/main/java/com/example/microprofile/faulttolerance

    APPLICATION_ROOT 是含有应用的 pom.xml 配置文件的目录。

  2. 进入新目录:

    $ cd APPLICATION_ROOT/src/main/java/com/example/microprofile/faulttolerance

    对于以下步骤,请在新目录中创建所有类文件。

  3. 创建一个代表 Coffee.java 的 Coffee.java 的简单实体,其中包含以下内容:

    package com.example.microprofile.faulttolerance;
    
    public class Coffee {
    
        public Integer id;
        public String name;
        public String countryOfOrigin;
        public Integer price;
    
        public Coffee() {
        }
    
        public Coffee(Integer id, String name, String countryOfOrigin, Integer price) {
            this.id = id;
            this.name = name;
            this.countryOfOrigin = countryOfOrigin;
            this.price = price;
        }
    }
  4. 创建包含以下内容的类文件 CoffeeApplication.java

    package com.example.microprofile.faulttolerance;
    
    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;
    
    @ApplicationPath("/")
    public class CoffeeApplication extends Application {
    }
  5. 创建一个 Jakarta 上下文和依赖注入 Bean 作为 CoffeeRepositoryService.java,包含以下内容:

    package com.example.microprofile.faulttolerance;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    import javax.enterprise.context.ApplicationScoped;
    
    @ApplicationScoped
    public class CoffeeRepositoryService {
    
        private Map<Integer, Coffee> coffeeList = new HashMap<>();
    
        public CoffeeRepositoryService() {
            coffeeList.put(1, new Coffee(1, "Fernandez Espresso", "Colombia", 23));
            coffeeList.put(2, new Coffee(2, "La Scala Whole Beans", "Bolivia", 18));
            coffeeList.put(3, new Coffee(3, "Dak Lak Filter", "Vietnam", 25));
        }
    
        public List<Coffee> getAllCoffees() {
            return new ArrayList<>(coffeeList.values());
        }
    
        public Coffee getCoffeeById(Integer id) {
            return coffeeList.get(id);
        }
    
        public List<Coffee> getRecommendations(Integer id) {
            if (id == null) {
                return Collections.emptyList();
            }
            return coffeeList.values().stream()
                    .filter(coffee -> !id.equals(coffee.id))
                    .limit(2)
                    .collect(Collectors.toList());
        }
    }
  6. 创建包含以下内容的类文件 CoffeeResource.java

    package com.example.microprofile.faulttolerance;
    
    import java.util.List;
    import java.util.Random;
    import java.util.concurrent.atomic.AtomicLong;
    import javax.inject.Inject;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    import java.util.Collections;
    import javax.ws.rs.PathParam;
    import org.eclipse.microprofile.faulttolerance.Fallback;
    import org.eclipse.microprofile.faulttolerance.Timeout;
    import org.eclipse.microprofile.faulttolerance.Retry;
    
    @Path("/coffee")
    @Produces(MediaType.APPLICATION_JSON)
    public class CoffeeResource {
    
        @Inject
        private CoffeeRepositoryService coffeeRepository;
    
        private AtomicLong counter = new AtomicLong(0);
    
        @GET
        @Retry(maxRetries = 4) 1
        public List<Coffee> coffees() {
            final Long invocationNumber = counter.getAndIncrement();
            return coffeeRepository.getAllCoffees();
        }
    
    
        @GET
        @Path("/{id}/recommendations")
        @Timeout(250) 2
        public List<Coffee> recommendations(@PathParam("id") int id) {
                return coffeeRepository.getRecommendations(id);
            }
    
        @GET
        @Path("fallback/{id}/recommendations")
        @Fallback(fallbackMethod = "fallbackRecommendations") 3
        public List<Coffee> recommendations2(@PathParam("id") int id) {
            return coffeeRepository.getRecommendations(id);
            }
    
        public List<Coffee> fallbackRecommendations(int id) {
            //always return a default coffee
            return Collections.singletonList(coffeeRepository.getCoffeeById(1));
        }
    }
    1
    定义重试到 4 的次数。
    2
    以毫秒为单位定义超时间隔。
    3
    定义在调用失败时要调用的回退方法。
  7. 进入应用程序的根目录:

    $ cd APPLICATION_ROOT
  8. 使用以下 Maven 命令构建应用程序:

    $ mvn clean install wildfly:deploy

    访问位于 http://localhost:8080/microprofile-fault-tolerance/coffee 的应用。

其它资源

  • 有关容错应用的详细示例,包括测试应用的容错性故障,请参阅 microprofile-fault-tolerance quickstart。