Java 客户端JAX-RS异步请求
我想实现一个异步JAX_-RS客户机 我有五个web服务Rest,我需要同时启动这些服务,而不必等待启动的第一个服务的响应 这是我的客户代码:Java 客户端JAX-RS异步请求,java,rest,asynchronous,client,jax-rs,Java,Rest,Asynchronous,Client,Jax Rs,我想实现一个异步JAX_-RS客户机 我有五个web服务Rest,我需要同时启动这些服务,而不必等待启动的第一个服务的响应 这是我的客户代码: public static void main(String[] args) throws InterruptedException { while (true) { for (int i=11;i<=15;i++){ launcherPS(i); }
public static void main(String[] args) throws InterruptedException {
while (true) {
for (int i=11;i<=15;i++){
launcherPS(i);
}
}
}
static void launcherPS(int id){
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
String name="LampPostZ"+id;
WebTarget target = client.target(getBaseURI(name));
System.out.println();
System.out.println("Launching of PresenceSensor "+id+"........");
String state = target.path("PresenceSensor/"+id).path("getState")
.request().accept(MediaType.TEXT_PLAIN).get(String.class);
System.out.println("state Presence Sensor "+id+" = " + state);
if (state.equals("On")) {
target.path("PresenceSensor/"+id).path("change").request()
.accept(MediaType.TEXT_PLAIN).get(String.class);
} else {
System.out.println("Presence Sensor shut down, state= "
+ state);
}
}
private static URI getBaseURI(String project) {// chemin de l'application
return UriBuilder.fromUri("http://localhost:8081/"+project).build();
}
}
publicstaticvoidmain(String[]args)抛出InterruptedException{
while(true){
对于(inti=11;i首先,为什么有一段时间是真的?一旦你的循环结束,所有的工作都做对了
您需要将每个调用放在自己的线程中
我的想法是:在线程中启动每个调用,然后等待每个响应,然后退出应用程序
您可以使用以下代码:
ExecutorService executor = Executors.newFixedThreadPool(5);
// Each call will be started here
List<Future<Integer>> futureList = new ArrayList<>();
for (int i = 11; i <= 15; i++) {
final int index = i;
Future<Integer> future = executor.submit(() -> {
// do your stuff here
return index;
});
futureList.add(future);
}
// This will wait for each call to finish
for (Future<Integer> integerFuture : futureList) {
integerFuture.get();
}
// everything's done, no need to wait indefinitely
ExecutorService executor=Executors.newFixedThreadPool(5);
//每个电话都将从这里开始
List futureList=新建ArrayList();
对于(int i=11;i{
//在这里做你的事
收益指数;
});
添加(未来);
}
//这将等待每个调用完成
for(未来集成:未来列表){
integerFuture.get();
}
//一切都已完成,无需无限期等待
我之所以将while设置为true,是因为我需要一个无限循环。事实上,我有5个状态传感器,我会一直让它们运行,因为我希望通过一个客户端同时启动它们,而不是创建5个客户端,每个客户端启动一个传感器。我设置的代码允许以连续方式启动传感器。即只有当第一个传感器完成其操作时,才会启动传感器。好吧,无论如何,您可以使用我编写的线程来实现异步。代码的语法错误Future-Future=executor.submit(()->{//do your stuff here return index;});
您使用的java版本是什么?我使用的是java版本8