java - spring async rest client orchestrate few calls -
i have following problem in service building object x in order build need make few http calls in order required data fill (each rest fills part of object.) in order keep performance high thought nice make call async , after calls done return object caller. looks this
listenablefuture<responseentity<string>> future1 = asyctemp.exchange(url, method, requestentity, responsetype); future1.addcallback({ //process response , set fields complexobject.field1 = "parserd response" },{ //in case of fail fill default or take ather actions })
i don't know how wait features done. guess standard spring ways of solving kind of issue. in advance suggestions. spring version - 4.2.4.release best regards
adapted waiting callback multiple futures.
this example requests google , microsoft homepages. when response received in callback, , i've done processing, decrement countdownlatch. await countdownlatch, "blocking" current thread until countdownlatch reaches 0.
it's important decrement if call fails or succeeds, must hit 0 continue method!
public static void main(string[] args) throws exception { string googleurl = "http://www.google.com"; string microsofturl = "http://www.microsoft.com"; asyncresttemplate asyncresttemplate = new asyncresttemplate(); listenablefuture<responseentity<string>> googlefuture = asyncresttemplate.exchange(googleurl, httpmethod.get, null, string.class); listenablefuture<responseentity<string>> microsoftfuture = asyncresttemplate.exchange(microsofturl, httpmethod.get, null, string.class); final countdownlatch countdownlatch = new countdownlatch(2); listenablefuturecallback<responseentity<java.lang.string>> listenablefuturecallback = new listenablefuturecallback<responseentity<string>>() { public void onsuccess(responseentity<string> stringresponseentity) { system.out.println(string.format("[thread %d] status code: %d. body size: %d", thread.currentthread().getid(), stringresponseentity.getstatuscode().value(), stringresponseentity.getbody().length() )); countdownlatch.countdown(); } public void onfailure(throwable throwable) { system.err.println(throwable.getmessage()); countdownlatch.countdown(); } }; googlefuture.addcallback(listenablefuturecallback); microsoftfuture.addcallback(listenablefuturecallback); system.out.println(string.format("[thread %d] line executed immediately.", thread.currentthread().getid())); countdownlatch.await(); system.out.println(string.format("[thread %d] responses received.", thread.currentthread().getid())); }
the output console:
[thread 1] line executed immediately. [thread 14] status code: 200. body size: 112654 [thread 13] status code: 200. body size: 19087 [thread 1] responses received.
Comments
Post a Comment