Take the following steps to complete this recipe:
- 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;
}
}
- Here, we defineĀ UserBean, which acts 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();
}
}
}
- Then, finally, we define a local endpoint that consumes 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());
}
});
}
}