Thursday, 15 March 2012

java - JAX-RS 2: using Guava ListenableFuture for async resources -



java - JAX-RS 2: using Guava ListenableFuture for async resources -

writing asynchronous endpoint in jax-rs 2 looks this:

@get public void asyncget(@suspended final asyncresponse asyncresponse) { new thread(new runnable() { @override public void run() { string result = veryexpensiveoperation(); asyncresponse.resume(result); } private string veryexpensiveoperation() { seek { thread.sleep(5000); } grab (interruptedexception e) { // ignore } homecoming "done"; } }).start(); }

however, method not nice since not declarative. have seen in jax-rs applications possible utilize google guava , write code this:

listeningexecutorservice executor = ...; @get public listenablefuture<string> asyncget() { homecoming executor.submit(new callable<string>() { @override public string call() { seek { thread.sleep(5000); } grab (interruptedexception e) { // ignore } homecoming "done"; } }); }

however, don't know how set jax-rs 2 implementation take kind of endpoint, , haven't figured out how other implementations have done it.

how configure e.g. bailiwick of jersey take kind of asynchronous declaration?

resume asyncrresponse in futurecallback:

@get @produces(mediatype.text_plain) public void asyncget(@suspended final asyncresponse asyncresponse) { listenablefuture<string> future = asyncget(); futures.addcallback(future, new futurecallback<string>() { @override public void onsuccess(string result) { asyncresponse.resume(result); } @override public void onfailure(throwable exception) { asyncresponse.resume(exception); } }); }

make sure asynchronous requests enabled in servlet configuration in web.xml:

<servlet> <servlet-class>org.glassfish.jersey.servlet.servletcontainer</servlet-class> ... <async-supported>true</async-supported> </servlet>

and utilize servlet 3.0 api.

java web-services rest asynchronous jax-rs

No comments:

Post a Comment