java - 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);
}
楼上的代码不起作用。这是我的看法。我的问题是有什么方法可以实现这样的功能
或者也许有人知道另一个可以构建这样的反应式休息代理的框架
解决方案
我找到了解决方案。 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);
}
推荐阅读
- c# - 两种不同类型的字典并转换为 JSON
- java - 错误:不兼容的类型:int 无法转换为 String
- java - 使用 JAVA Spring Boot 创建评论系统后端服务器
- java - Java Swing - 方法 getComponents 仅返回一个组件
- python - 如何使这个函数以数组数组作为输入用 numba 编译?
- javascript - 在逐个节点的基础上设计 react-treebeard
- typescript - for 循环内的 const
- java - 使用 Geonetwork 元数据完整视图时出现 JAVA 堆空间错误
- android - 如何截取videoView当前帧的截图?
- node.js - 如果 curl 请求是 404 或 403,则用于 curl 请求的 Node.js childprocess.execSync 不返回错误