I am working on creating an API that could potentially have a large number of requests per second, and some requests may require a lot of computation (complex reports). I was asked to put together a small prototype as proof of concept. I am using Spring Boot with Jersey as my implementation of JAX-RS. I used to do something like this with Spring MVC.
@RequestMapping(value = "/dashboard", method = RequestMethod.GET) public DeferredResult<String> showDashboard(Model model) { DeferredResult<String> result = new DeferredResult<>(); model.addAttribute("testObj", new User()); result.setResult("home/dashboard"); return result; }
I tried this with Jersey and it seems to have worked, or at least he was not mistaken.
@GET public DeferredResult<String> getClients() { DeferredResult<String> deferredResult = new DeferredResult<>(); deferredResult.setResult("Nothing! But I'm Async!"); return deferredResult; }
However, all the examples I saw to handle operations asynchronously in Jersey look like this.
Produces(MediaType.TEXT_PLAIN) public void get(@Suspended final AsyncResponse response) { // This call does not block. client.callExternalService( // This callback is invoked after the external service responds. new Callback<string>() { public void callback(String result) { response.resume("Result: " + result + ".n"); } }); }
My main question is what is the difference between these three pieces of code behind the scenes, even if they exist. Do they all do the same thing?
Is there a better way to execute async? I also saw the use of Future in Java, but never used it.
UPDATE:
I have the following code in a Jersey controller that works.
@GET public String getClients() { return "Nothing, I'm Sync!"; } @GET @Path("/deferred") public DeferredResult<String> getClientsAsync() { DeferredResult<String> deferredResult = new DeferredResult<>(); deferredResult.setResult("Nothing! But I'm Async!"); return deferredResult; } @GET @Path("/async") public void getClientsJAXRSAsync(@Suspended AsyncResponse response) { new Thread(() -> { response.resume("I am Async too! But I am using @Suspended"); }).start(); }
As for my main question, what is the difference between the two? My understanding of DeferredResult is the Spring thing, so I'm not sure if it is worth using with Jersey, although I use Jersey + Spring.
spring asynchronous spring-boot jersey
greyfox
source share