con 2107- think async: embrace and get addicted to the asynchronicity of ee

Download CON 2107- Think Async: Embrace and Get Addicted to the Asynchronicity of EE

Post on 23-Jun-2015

157 views

Category:

Technology

2 download

Embed Size (px)

DESCRIPTION

This presentation covers the whole spectrum of Asynchronous processing present in Java EE through introducing a use case. The coverage starts with introducing the usecase and showing how a mix of JMS, MDB and Async Servlet can address the requirement of the use case. The session will also cover asynchronicity in JAX-RS as well as covering NIO in Servlet 3.1

TRANSCRIPT

  • 1. EmbraceandGetAddictedtotheAsynchronicityofEECopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|ThinkAsyncMasoudKalali,SoEwareEngineer,ORACLE,@MasoudKalal

2. SafeHarborStatementThefollowingisintendedtooutlineourgeneralproductdirecNon.ItisintendedforinformaNonpurposesonly,andmaynotbeincorporatedintoanycontract.Itisnotacommitmenttodeliveranymaterial,code,orfuncNonality,andshouldnotberelieduponinmakingpurchasingdecisions.Thedevelopment,release,andNmingofanyfeaturesorfuncNonalitydescribedforOraclesproductsremainsatthesolediscreNonofOracle.Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| 3. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|ProgramAgendaIntroducNonWhytothinkAsyncAsimplecaseofusingAsyncJMS(2.0)AsyncServletAsyncJAX-RSAsyncEJBs1234567 4. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|SpeakersMasoudKalali SoEwareengineer,author,blogger LongadvocateofGlassFishandJavaEE Tweetsat@MasoudKalali 5. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|WhytothinkAsync? Tobe]ermodelwhatwedevelopfor Tofurtherdecouple EaseofadministraNon Easeoftuning Easeofmaintenance Improveconsumersexperience AnAPIconsumer AdirectGUIforhumanuse etc. 6. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|JavaEEAndASynchronicity LongpresentJMS Tobeusedalmosteverywhere Servlet3.0/3.1 AsynchronousServlets NoneblockingIO JAX-RS2.0 Serverside Clientside AsynchronousSessionBeans Serverside Clientside 7. AsimpleasynchronousnourishedusecaseCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|ClientAsyncServletCacheQueryProcessorJMSQueueJMSQueueMDBID,AsyncContextQueryRequestsinJMSChunksConsumeresultchunksandofQueryresults1senditbackviaAsyncContext12.1324.8.7.6.5.NoHA/Faulttoleranceconsidered,ThisIsaverybasicblockdiagramtohelpwiththepresentaNon 8. AsimpleasynchronousnourishedusecaseMoredetailsoftheMessagingcomponentsCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| OneJMSqueueforsendingthequeryrequests OneJMSqueuewhichwillgetchunksofqueryresults AnMDBwhichwillconsumethequeryresultmessages UsesthecacheandtheidinthemessagetopickuptherightAsyncContext Aslongasthemessagedoesnotsayitisdoneitwillnotconcludetheresponse CompletetheresponsewhenJMSmessageimplies 9. AsimpleasynchronousnourishedusecaseCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|MoredetailsoftheServletcomponents AsynchronousServletreceivingtherequests CachingtheAsynContextandaqueryId SendingtheQuerymessagetotheJMSqueue IncludingthequeryId LeaveittotheMDBtoupdatetheresponse HaveaAsyncListenertosendproperresponseifNmeouts 10. AsimpleasynchronousnourishedusecaseCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|Somebasicsontheclientside Abrowser Canbe ASSEclient ACOMET,LongPollingrequest 11. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|JMS(2.0)Abriefoverview 12. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|JMS:AbriefoverviewI Broker Message Queue Producers Consumers Topic Publishers Subscribers AccessiblefrominsideoroutsideaJavaEE 13. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|JMS2.0:Abriefoverview: MulNpleConsumersAllowedontheSameTopicSubscripNon DeliveryDelay SendingMessagesAsynchronously Sendthemessageandgetcallbackwhenitisacknowledgedbybroker JMSXDeliveryCountmessagepropertyNolongeropNonal StandardMDBConfiguraNonProperNesaspartof@MessageDriven desNnaNonType subscripNonDurability acknowledgeMode subscripNonName ... 14. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|Servlet3.0Asynchronousservlet 15. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|Servlet3.0Asynchronicity Whywewantit Morethroughput Be]erarchitecturemapping Howitworks @WebServlet.asyncSupported,async-supportedinXMLconfig! AsyncContext AsyncListener 16. Servlet3.0Asynchronicity:AsyncContext AddingCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|listeners Doingrequestdispatching AccessingServletRequest AccessingServletResponse Concludingtherequest/response Semng,gemngNmeouts 17. Servlet3.0Asynchronicity:AsyncListener GetcallbackonimportanteventsonanasyncrequestprocessingCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| onComplete(AsyncEventasyncEvent) onError(AsyncEventasyncEvent) onStartAsync(AsyncEventasyncEvent) onTimeout(AsyncEventasyncEvent) 18. Servlet3.0Asynchronicity:Ali]lebitofcode@WebServlet(asyncSupported=true,value=/query-servlet")publicclassQueryServletextendsH]pServlet{protectedvoiddoGet(H]pServletRequestrequest,H]pServletResponseresponse)throwsServletExcepNon,IOExcepNon{Stringid=...;cache.put(id,request.startAsync());sendQueryMessage(id,request);}}Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| 19. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|Servlet3.1Non-blockingIO 20. Servlet3.1:Non-BlockingIO WhyCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|dowewantit? Howdoesitwork? ReadListener:Toreadinbounddatawhenavailable WriteListener:Towritedatawhenpossible ChangesinServletOutputStream isReady() setWriteListener() ChangesinServletInputStream isFinished() isReady() setReadListener() 21. Servlet3.1:Non-BlockingIO:ReadListener TogetcallbacksonServletInputStreamevents onDataAvailable OnAllDataRead onErrorCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| 22. Servlet3.1:Non-BlockingIO:WriteListener TogetnoNfiedonServletOutputStreamevents onError onWritePossibleCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| 23. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|AsyncronicityinJAX-RS2.0 Whywouldweneedit? Howdoesitwork? @Asynchronous ExecuNonContextforprogrammaNcdecisiontodoornottodoasync AsyncResponse @Suspended CompleNonCallback ConnecNonCallbck 24. AsyncronicityinJAX-RS2.0:Server-sideIHowtomarkaresourceasAsynchronous OnCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|theserverside: @Asynchronous:Annotateasub-resourceasAsynchronous AsyncResponse:ProvidesresultsanacNonsontherunningrequest semngNmeout registeringcallbacks resume,cancelsuspendedrequestprocessing updaNngtheresponse @Suspended:ToinjectasuspendedAsyncResponseintoasub-resourceparameter 25. AsyncronicityinJAX-RS2.0:Server-sidesimplecodeServerCode:@Path("/api/query")publicclassMyResource{@ContextprivateExecuUonContextctx;@GET@Produce(applicaUon/json)@Asynchronous@Path(api/matching-query)publicvoidprepMatchingQueryResult(@SuspendedAsyncResponsear,@QueryParamStringp1){executor.submit(newRunnable(){Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|publicvoidrun(){JsonObjectresponse=getQueryResult(p1);ctx.resume(response);//containerthreadpicksupandconUnue}});ctx.suspend();//SuspendconnecUonandreturn}} 26. AsyncronicityinJAX-RS2.0:client-sidesimplecodeFuturefuture=client.target(/api/query/matching-query).queryParam(...).request().async().get(JsonObject.class);try{JsonObjectqueryResult=future.get(30,TimeUnit.SECONDS);}catch(TimeoutExcepNonex){//}Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|Client-Sidewithfuture 27. AsyncronicityinJAX-RS2.0:client-sidesimplecodeClient-SidewithcallbackFuturefuture=client.target(/api/query/matching-query).queryParam(...).request().async().get(newInvocaNonCallback(){@Overridepublicvoidcompleted(JsonObjectresponse){//InvocaNonhappensandsomeresponseisback(404,200,etc.)}@Overridepublicvoidfailed(Throwablethrowable){//InvocaNonfails(clientside)Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|}}); 28. AsyncronicityinJAX-RS2.0:Server-sideII SingleCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|CompleUonCallbackmethodinterface voidonComplete(Throwablet) signalcompleNonofservingarequest 29. AsyncronicityinJAX-RS2.0:Server-sideIII SingleCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|ConnecUonCallbackmethodinterface voidonDisconnect(AsyncResponsedisconnected) signalsinterrupNoninclientconnecNonbeforecompleNon 30. AsynchronousAndlongrunningjobsinRESTDontkeepunnecessaryresourcesforwherenotneeded!Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| MulN-steplongrunningjobsnotsuitablewithJAX-RSAsync Send202whereresponseisnotreadywithLocaNonheader IntelligentenoughclientcanquerytheresourceLocaUonwiththegivenRetry-Aderheader 31. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|EJB3.1AsynchronicityinSessionBeans 32. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|AsynchronicityinEJB3.1 Worksonsessionbeans fireandforget UsingFuturetodecideoncompleNon AsyncResultascontainerspecificvehicle PassestheresulttoFuture Assimpleasusing@Asynchronousonmethod/bean MethodshouldreturnFuture ClientcanpollthefutureforCompleNon 33. AsynchronicityinEJB3.1:SimplecodesampleServer-sidecode@StatelesspublicclassQueryProcessor{@AsynchronouspublicFutureprocessQuery(QueryCritcrit){try{QueryResultresult=prepQueryResult(crit);returnnewAsyncResult(result);Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|}catch(ExcepNone){//handlereturnnewAsyncResult(FAILURE_RESULT);}}} 34. AsynchronicityinEJB3.1:Simplecodesample@InjectQueryProcessorqueryProcessor;privateJsonObjectprepareQueryResult(String...params){QueryCritcrit=newQueryCrit(params)Futureresult=queryProcessor.prepQueryResult(crit);//polltheFuture..Thereisnocallbackhere...}}Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|cliet-sidecode 35. Copyright2014,Oracleand/oritsaffiliates.Allrightsreserved.|JavaEE7andSSEAsynchronicityinSSE 36. Server-SentEvents HTML5component Clientsubscribetoeventsource UnidirecNonalchannelbetweenserverandclient Eventscanbestreamedfromservertoclientwhenhappens ConnecNonstaysopen eventhandlingonclientsideCopyright2014,Oracleand/oritsaffiliates.Allrightsreserved.| onMessage onError etc. SubscripNonresuming 37. Server-SentEvents CanbedevelopedusingaplainServlet usetherightmediatype usethecorrectmessageformat JerseyprovidessupportnotJAX-RSyet ServersidetoturnaJAX-RSendpointtoSSEbroadcaster ClientsidetosubscribeandconsumeSSevent