首页 > 解决方案 > Apache cxf rest客户端代理可以与反应接口一起使用吗

问题描述

假设我有一个描述另一个休息服务的接口。它看起来像这样:

@Produces("application/json")
public interface PetApi {


    @GET
    @Path("pet/{petId}")
    String getPet(@PathParam("petId") Long petId);
}

当我调用它时它工作正常:

    private static void testPet() {
        PetApi petApi = JAXRSClientFactory.create("https://petstore.swagger.io/v2", PetApi.class);

        String petDescr = petApi.getPet(1L);
        System.out.println(petDescr);
    }

现在我想改进这个代码,以便在反应流中工作。apache CXF 可以为响应式代码生成代理吗?以这种方式调用代码将如下所示:

    private static void testPet() {
        PetApi petApi = JAXRSClientFactory.create("https://petstore.swagger.io/v2", PetApi.class);

        CompletionStage<String> petDescrCs = petApi.getPet(1L);
        petDescrCs.thenAccept(System.out::println);
    }

外部休息服务的接口是:

@Produces("application/json")
public interface PetApi {


    @GET
    @Path("pet/{petId}")
    CompletionStage<String> getPet(@PathParam("petId") Long petId);
}

楼上的代码不起作用。这是我的看法。我的问题是有什么方法可以实现这样的功能

或者也许有人知道另一个可以构建这样的反应式休息代理的框架

标签: javarestjax-rscxffeign

解决方案


我找到了解决方案。 https://github.com/OpenFeign/feign从 10.8 版本开始可以进行响应式调用。

请参阅https://github.com/OpenFeign/feign#async-execution-via-completablefuture

应用于问题中的代码...

依赖项:

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>11.2</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-jaxrs</artifactId>
            <version>11.2</version>
        </dependency>

界面:

@Produces("application/json")
public interface PetApi {


    // Reactive method. Work only with CompletableFuture(not work with CompletionStage)
    @GET
    @Path("pet/{petId}")
    CompletableFuture<String> getPetCs(@PathParam("petId") Long petId);

    // Non reactive method
    @GET
    @Path("pet/{petId}")
    String getPet(@PathParam("petId") Long petId);
}

调用示例:

    private static void reactiveTest() {
        PetApi petApi = AsyncFeign.asyncBuilder()
                .contract(new JAXRSContract()) // JAX-RS contract for fegin
                .target(PetApi.class, "https://petstore.swagger.io/v2");
        CompletionStage<String> petDescrCs = petApi.getPetCs(1L);
        petDescrCs.thenAccept(System.out::println);
    }

    private static void noneReactiveTest() {
        PetApi petApi = AsyncFeign.asyncBuilder()
                .contract(new JAXRSContract()) // JAX-RS contract for fegin
                .target(PetApi.class, "https://petstore.swagger.io/v2");
        String petDescr = petApi.getPet(1L);
        System.out.println(petDescr);
    }

推荐阅读