How to do it...

  1. First, we create a User POJO:
public class User implements Serializable{

private Long id;
private String name;

public User(long id, String name){
this.id = id;
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
  1. Here, we define UserBean, which will act as a remote endpoint:
@Stateless
@Path("remoteUser")
public class UserBean {

@GET
public Response remoteUser() {
long id = new Date().getTime();
try {
TimeUnit.SECONDS.sleep(5);
return Response.ok(new User(id, "User " + id))
.build();
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
return Response.ok(new User(id, "Error " + id))
.build();
}
}

}
  1. Then finally, we define a local endpoint that will consume the remote one:
@Stateless
@Path("asyncService")
public class AsyncService {

private Client client;
private WebTarget target;

@PostConstruct
public void init() {
client = ClientBuilder.newBuilder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
target = client.target("http://localhost:8080/
ch10-async-jaxrs/remoteUser");
}

@PreDestroy
public void destroy(){
client.close();
}

@GET
public void asyncService(@Suspended AsyncResponse response){
target.request().async().get(new
InvocationCallback<Response>() {
@Override
public void completed(Response rspns) {
response.resume(rspns);
}

@Override
public void failed(Throwable thrwbl) {
response.resume(Response.status(Response.Status.
INTERNAL_SERVER_ERROR).entity(thrwbl.getMessage())
.build());
}
});

}

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.61.218