2.21.5. 代理
代理是 RESTEasy 扩展,支持直观的编程样式,用特定于应用的接口调用取代通用 JAX-RS 调用。代理框架扩展为包括 CompletionStage 和 RxJava2 类型 Single、Observable 和 Flowable。以下示例演示了 RESTEasy 代理如何工作:
示例 1:
@Path("")
public interface RxCompletionStageResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<String> getString();
}
@Path("")
public class RxCompletionStageResourceImpl {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<String> getString() { .... }
}
public class RxCompletionStageProxyTest {
private static ResteasyClient client;
private static RxCompletionStageResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy = client.target(generateURL("/")).proxy(RxCompletionStageResource.class);
}
@Test
public void testGet() throws Exception {
CompletionStage<String> completionStage = proxy.getString();
Assert.assertEquals("x", completionStage.toCompletableFuture().get());
}
}
示例 2:
public interface Rx2FlowableResource {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable<String> getFlowable();
}
@Path("")
public class Rx2FlowableResourceImpl {
@GET
@Path("get/string")
@Produces(MediaType.TEXT_PLAIN)
@Stream
public Flowable<String> getFlowable() { ... }
}
public class Rx2FlowableProxyTest {
private static ResteasyClient client;
private static Rx2FlowableResource proxy;
static {
client = new ResteasyClientBuilder().build();
proxy = client.target(generateURL("/")).proxy(Rx2FlowableResource.class);
}
@Test
public void testGet() throws Exception {
Flowable<String> flowable = proxy.getFlowable();
flowable.subscribe(
(String o) -> stringList.add(o),
(Throwable t) -> errors.incrementAndGet(),
() -> latch.countDown());
boolean waitResult = latch.await(30, TimeUnit.SECONDS);
Assert.assertTrue("Waiting for event to be delivered has timed out.", waitResult);
Assert.assertEquals(0, errors.get());
Assert.assertEquals(xStringList, stringList);
}
}