Vous êtes sur la page 1sur 14
azaro18 eee sero arg exw Jason Face veins ‘sree “sion Sec 14. Conan overt Fas penne 15, Jam Sefe etna wecrab hosenore Panty cron Bare 24 Rung te Enero eon Era ‘npensecy een Exar ‘teemany been Cea aria A Aptos | rt Secty 4. ting Sate Sect Alene hoseaere “ 2 va Scr Abed Tepes ‘oboe 16 sa eanage Senn Expl mS Appstons| ‘Sine Rein Ema Welling Simple JMS Applications - The Java EE 6 Tutorial IX ti The Java EE 6 Tutorial = Java eoo Writing Simple JMS Applications ‘This section shows how io crest, package, and run simple JMS clon that ae packaged as application clients {and deployed'o a Java EE server. The chenta demonstrate the basic tasce JMS appleation must peor + Creating 2 connection and a session + Creating message producers and consumers + Senin and ceiving messages Ina Java EE application, some of those tasks are porformod, in whol o in pat, bythe container. you arn ‘about these tasks, you ml have a good bass for understancing how a JMS apoicaton works on tre ava EE Platorn, Each example uses to cllens: one that sands messages and one that receives them. You can run the cents In NetBeans IDE orin two terminal windows, \When you wie 3 JMS clon to run nan entorprse bean application, you use many ofthe same maths in ‘ue the same sequence a for an applleaton chet, However, there ae some ignieant ifferonces, Using ‘hous APri viva F Apottons desorbes these difrences, and his chapter provides examples that sate them. ‘The examples forbs section ae inthe futnstall/exazp ee) jma/sispe/ drctory, under te fotowing four subdirectories producer Ressagebrowser A Simple Example of Synchronous Message Receives: ‘This section descrioes the sending and receiving clentsn an example that uses the rocoiwe method to consume massages synchonously Ths secon thon explains naw fo compl, package, and run the cients Using the GlassFish Server ‘Te folowing subsections describe the steps in cestng an running the example Writing the Clients for the Synchronous Receive Example ‘The sondng cont, produces /r2/jave/Pzoducer. java, paforms the flloning stops: 4. njacts resources fora connection factory, queue, and toni: anesource (Lookup ~ ")ae/Connecticntactory") private static Connectionfactory connect ionFactorys Gheaource (Lookup ~ "jas/Queus")private static Queue queues Gkesouree (Lookup = "Jas/Toplet)private static Topic topic: 2, Revives and verfies command-ine arguments that pect the desthaton type and he numberof ‘arguments: inal ant NoN_Nscs Seeing desetype ~ args(0]; System.ovt.princin("Sestiration type ie" + desttype)s AEC! { dasetype.equals *quoue"l |) dosttypeveqeale(*topic) ) } 1 systensere peintin(eArgunent mist be \rqueue\” or "+ *\"copio\ systensenitilh > Af (arge.tenath == 21 NOMLMSGS = (now Integer targs[}}) .Antvalued > stse | > 8. Assgns either he queue or the topic o a destination objet, based onthe specified destination type EE Idosttype.equale ("guece"!) 1 Gest (Destination) queus; Fete | Gest = (Destination) topic: ' 1 Esteh (exception ef Syaten-ers-printin ("Error setting dagtination: "+ e.testeing(tl7 hitpstidocs.orace.com/javaeet6/ttoriaidactoncta.html ana azaro18 Welling Simple JMS Applications - The Java EE 6 Tutorial MS Anne Oc fo e-printstackteace() th yneonsue Rca Systennextt (ls ‘ring tn Cl , Syoctrnom ReciveEamoe —4, Cragtas a Connect ion and a Senator: iertage consumes Connection connection = connectiontactory .createconnection(): ‘rig Car tbe Sesaton session = connection.crestaSeaston( “lyncronos tacts false, sean Seaaion.AUTO_ACKNOWDEDGE) ‘aypeonminasClersUslo 5, Greggs atessayeProduces anda TexiMessage! MesaageProducer producer = seasion.czeateP reduces (dest) TextMessage reasage ~ sossion.createfextNcssage ‘Syncstoncune CeriUsing 6 Sed one or more messages to the destination “epoy ant te Sane er for int 2 = op £ < MUM mses) 644) “ye syrehoraus Roce pessage.setText ("This se neasage "+ (1+ 1) 4" from producer"); Eranpl Ung tend e Systen.out.printin ("Sending sesuege: "+ meveaye.cet Text (1)? septic Commons producer. send (zeasage)? A single Example of romaing , ‘Weng th Chet forthe 7. Sends an amply control message to indicate the end ofthe mossage stream: ‘ToRanthenaceagensoneas produces. send aession.createlesaage () loiter tacragetensas Sending an ampty message of no specifed type Isa convert way to ndcae othe consumer hat ho ‘han Ung hand he final massage has arived nn {Closes the conection ina Fina 1y Hoc, samatalycsng th session ad voseagaProcucer ects Amite bee 2 eamaaty or ee ey comestion-edove (7 ) Shan in nt olen (aecception 6) 11 ‘NeiBieans IDE * ' ‘The rocaving lot, eyachconsumer/ex2/ jave/SyzehCeneuner. java, performs the following tops te eee 1 Iroc sources fora connection factory, queue, and tpi. in Reb A Aeon 2. Assigns ether he queue othe tole a destnaton abject, based on he speed desthaton type. MGmnsngataneiny 3. Creates coanectson anda session TansciesvernpieWiiy Crea a Hessageconatnes hn 5, Starts th connection, causing message dolar to bog: ia tears DE onnectien.star= ths hoa {5 Recelves the messages sent othe destination ul the endo message-steam contol message it recaved Tofu ranean cea white (eauel ( anabeas iaseage m\= sonsuner.recetve(Lhz ten reenact Parmer) gta eae Tee instanceof Texttessage) Senne ‘becoaye = (lextlacsagel as se lean Tat ns a1 101, Syatenvovt peintin("Readlag message: * + message eae ) ene’ arg etn Ce , cores ; Cearg there rac Because the contol messages nota Zex:secsage, the recaving lent temas the whe oop and seeps foe recohing mastapes ae te contra message aves. Oertchcnesatarags Example 7. Closes the connection in @ £1 block, automatically closing the session and mieasageConsumer. et ‘The receive method can be used in several ways to perform a synchronous receive. you specty no ‘Tominiieciievessionnae —AfQUMERIS OF an argument of 0, the mathoa Blocks indeinely unt a message aves: eater teaeage © = consumer eecedve(O): ‘oNelason Tit teete IS AP16% Fara siple can thismay na mater. But ou do not wan your eppteaton oconstme system resources unnecessary, use a imed synchzenous receive. Do one of fo following ere nag Callie eccts matad wha Umeou argument greater an Message m= consuner.receive(i): // 1 mLlLiseoone Casa he A “ o cea gang Calltbe xecesvtitast method which receives a message ony fone i valle: Siete Mesaage m = consuner.receivetstait (1 hitpstidocs.orace.com/javaeet6/ttoriaidactoncta html ana 8/23/2018 Welling Simple JMS Applications - The Java EE 6 Tutorial og Revacs ee ‘The Synchconsunes cent uses an indole wh. lop to rocoive messages, caling zecesve wih @ onto ty Eagle timeout argurent. Calling receivetictiait would have tw same offer, Crate Starting the JMS Provider hoinoe \Whon you us the GlassFish Server, your JMS provider isthe GlassFish Sorver. Start tha server as described in ena ira nebesIO® _Siartng and Stopping he GasFish Sone Erne erodes JMS Administered Objects for the Synchronous Receive Example etsgee tm a Horse Sone ‘This example uses he falling JMS administered objects: ‘Ebel esee + A connection factory wtebame + Two destration rescues: tope and a queue [NetBeans IDE and the Ant ask forthe JMS examples create needed JMS resources wien you deploy the pplcaions, using alle named setio/slasatiah-rosources.,nl Ths fie fe most easly ceated using [Netfeans IDE, alfnough you can crete by hand notte conan rane You can algo use the aoscnin cxeate~ins-vesouece command to eoate resources, the asadsin List= ‘gle UsrgtoBensl0® —_ymarrescurces command to display her names, andthe asadn:n dolete~yns-resource command 6 Toni cenmsnene remove then. ongpsann connpc nn depayen -T@ Create JMS Resources Using NetBeans IDE aeecereieccecectcton Follow these stops to create @ JMS resource in GlassFish Server using NotBeans IDE. Repeat these stops fr rons ‘eh resource you need, trate oaecoreow The example applications inthis chapter already have the resources, eo you will ned o flow these steps only votes Chee vahen you create your oun apoio. 4. Rightelick the project fr which you want to ereate resources and choose New, then choose Other ‘The Now File wizard opens, pone 2 Under atagore, select Swinrmvenonie Unger El Rp ste Resource, Centr teenete Thane Ae = Reena pee srsbe-nunmtessng Inthe 4NOLName el ype the name ofthe resource. "kisses" pyeoovrton MS esouce names ean ih TASTE setet the radi bution forthe resource ype, TeDkeooemener seems Namal i ter Javan See -Oueue, Joven Shs Top.e. oF sen. Connec onan Ae 6. coe Hox 5. Uv Hosa ‘he Me Papen pon coons St Bae ocr Coo Sty Exam 7. Fora queue or topic type a name for a physical queue in the Value fed for the Name property. £2 Dua Ting Cave ha Eero 5, Du Foret ane Say Exar You can type any value for this requved fe hr Connection factories have no required properties. na few situations, cussed in lar sections you may the -2e0u7 80, 9m! Is erated in your projec. ina dretory named s2=~p. under he Server Resources node. hs le exis, resources are created Sutomaticaly by NetBeans IDE when you deploy the project To Delete JMS Resources Using NetBeans IDE ‘Inthe Services pane, expand the Servers noda, then expand the GlassFish Server 3+ node. 2 Expand the Resources node, then expand the Connector Resources nod 43. Expand tho Admin Object Resources nodk 5. Expand the Connector Connection Pools node. 6. Right-lck any connection factory you want to remove and select Unregister. Every connection factary has both a connector connection pool and an associated connector resource, ‘winan you remove the connector connecton poo, he resource is removed aulomaicaly. You can very ‘ne removal by expanding the Connector Resources node. Running the Clients for the Synchronous Receive Example ‘Torun these examples using te Glass'sh Server, package each one in an application cent JAR fe. The Application cont IAR He requires marses flo, cated inthe sec/cone ereclory foreach example, along lth the ona le, ‘The buttd. xn Me foreach example contains Ant targets that compile, package, and deploy the example. The targets place the .c1 nes fle fr the example nthe but 1a/sa> afectory. Then the targets use the a= ‘command to packaga the clas fle and the manfst fle inan application clan JAR fle ‘Bocause the examples use the common interfaces, you car run them using either a queue or a tpl ‘To Build and Package the Clients for the Synchronous Receive Example Using NetBeans IDE 4. From the File menu, choose Open Project. 2 Inthe Open Project datog, navigate t: hitpstidocs.orace.com/javaeet6/ttoriaidactoncta html ata