Tải bản đầy đủ - 0 (trang)
Chapter 27. Introduction to Message-Driven Beans

Chapter 27. Introduction to Message-Driven Beans

Tải bản đầy đủ - 0trang

27.1JavaMessagingService

AsdiscussedinChapter3,JMSisaJ2EEstandardthatprovidesa

vendor-neutralwayofsendingandreceivingasynchronousmessagesin

adistributedenvironment.JMSprovidesanAPIforaccessingMOM

systemssuchasIBMWebSphereMQ.J2EE1.3requiresthatan

applicationservermustprovideaJMSprovider.Incompliancewiththis,

WASprovidesasimplemessagingprovider(WebSphereEmbedded

Messaging)thatisderivedfromWebSphereMQ,butdoesnotprovideall

ofthefeaturesofWebSphereMQ,suchasclusteringoradvancedqueue

managementfacilities.

InadditiontosupportingdevelopmentonbothWebSphereEmbedded

MessagingandWebSphereMQ,WSADprovidestheMQSimulatorfor

Java(MQSimulator).MQSimulatorsupportspoint-to-point(P2P)and

publish-and-subscribe(pub/sub)withpersistentandnonpersistent

messages,butonlywithinasingleTEserverinstance.MQSimulatorisa

usefuladditiontoWSADthatwillallowustotestourMDBandJMS

clientswithinWSAD.

JavaapplicationsthatuseJMSarecalledJMSclients.Justas

WebSphererequiresaJavadatabasedriverforconnectiontoa

database,WebSpherealsorequiresaJavaconnectiontoanunderlying

MOMthatiscalledtheJMSprovider.AJMSclientthatsendsamessage

iscalledaproducerandaJMSclientthatreceivesamessageiscalleda

JMSconsumer.ItispossibleforasingleJMSclienttobeboththe

producerandtheconsumerofamessage.



27.1.1JMSIsAsynchronous

AttheheartofJMSisthefactthatitallowsforasynchronousmessaging.

ThismeansthataJMSclientcansendamessagewithouthavingtowait

forareply.Thisisquitedifferentfromthesynchronousmessagingof

JavaRMIandsimilartechnologies.RMIisanexcellentchoicefor



creatingtransactionalcomponents.Eachtimeaclientinvokesabean's

methodthecurrentthreadontheclientisblockeduntilthemethodis

finished.However,thiscreatesatime-baseddependencyontheEJB

server.IftheEJBserverisunavailable,themethodwillnotcomplete

successfully.Further,ifthetraffictoyourEJBisbursty(meaningithas

veryhighpeaksandlongperiodsofquiescence),thenyourserverwillbe

underutilizedattimesandperhapsoverwhelmedattimes.Thesetwo

factorsleadtoatightcouplingbetweentheclientandserver.This

couplingisrelaxedbecauseJMSisasynchronous.

InJMS,aclientcanfireandforget.AJMSclientcanputamessageona

queueorpublishamessagetoatopicandgoontootherimportantwork.

Topicsandqueuesarereferredtoasdestinations.Inthisway,clients

sendingmessagesaredecoupledfromclientsreceivingthem.

WhenusingaJMSdestination,theJMSclientcanbeassuredthatthe

messagewillbedeliveredevenifdowntimeoccurs.Thisdurabilityof

messagescanbeoptionallyspecifiedonbothqueuesandtopics.The

durabilityfeatureofJMSisprobablythesecondmostattractiveaspectof

usingJMSforsolvingcertainenterprisesituations.



27.1.2JMSMessagingModels

TwomessagingmodelsareavailableinJMS:pub/subandP2P.Pub/Sub

isintendedforaone-to-manybroadcastofmessages;P2Pisintended

forone-to-onedeliveryofmessages.Intalkingaboutmessaging,the

creatororsenderofthemessageisreferredtoastheproducerandthe

receiverofthemessageiscalledtheconsumer.



27.1.2.1Publish-and-Subscribe

Inpub/sub,asingleproducersendsamessagetomanyconsumers

throughavirtualchannelcalledatopic.Theproducerisunawareofhow

manyconsumers,ifany,mightreceivethemessage.Consumerscan

onlyreceivethemessageiftheyhavesubscribed.



27.1.2.2Point-to-Point

P2PmessagingallowsJMSclientstosendandreceivemessagesboth

synchronouslyandasynchronouslyviavirtualchannelsknownas

queues.Aqueuemayhavemultiplereceiversbutonlyonecanreceive

themessage.



27.2JMSAPIBasics

Wecertainlycan'tcoveralloftheinsandoutsofusingtheJMSAPIin

thischapter;thatsubjecthasfilledentirebooks.Instead,wereferthe

interestedreaderto[Monson-Haefel]or[IBM-JMS]forthedetailsofthe

API.Luckily,theAPIisbasedupononlyafewsimpleconcepts,whichwe

canfleshoutinthecontextofaverysimpleexample.Onceyou

understandthisbasicexampleyou'llbeinbettersteadtounderstandthe

morecompleteexamplepresentedlaterinthechapter.

Asmentionedpreviously,thefundamentalactionofsendingamessage

inJMSinvolvesusingamessageproducertoplaceamessageona

destination.Let'sfirstlookathowtheseconceptsareimplementedin

JMSandhowyoucanusetheminyourprograms.

Thefirstconceptweneedtointroduceishowtofindadestination.

DestinationsareheldintheJNDInamespace,justasEJBsare.The

followingsyntaxcanbeused(notethatitisnearlyidenticaltolocatingan

EJBhomeinterface).

InitialContextctx=newInitialContext();

Objecto=ctx.lookup("jms/QOrTopicName");

javax.jms.QueueaQueue=(javax.jms.Queue)

java.rmi.PortableRemoteObject.narrow(o,javax.jms.Queue.class);



However,unlikeanEJB,youcan'tjuststartusingaQueuetosend

messages.RememberthatyoumusthaveaMessageproducertosend

messagestocreateamessageproducer,youmustfirstobtaina

connection.Inthatrespect,JMSismuchmorelikeJDBC.Thesyntaxfor

obtainingaConnectionisshownnext:

//LookuptheQueueConnectionFactoryinJNDI



Objecto=ctx.lookup("jms/ivtQCF");



javax.jms.QueueConnectionFactoryqcf=(javax.jms.QueueConnecti



java.rmi.PortableRemoteObject.narrow(o,

javax.jms.QueueConnectionFactory.class);

//CreateaQueueConnection

javax.jms.QueueConnectionconn=qcf.createQueueConnection();



Again,likeinJDBC,youthenneedtoobtainanobjectfromaconnection

thatyoucanworkwith.TheJMSSessionobjectisthetransactional

objectthatyouusetocreatemessageproducers.Whiletheobjects

we'veseenpreviously(Queues,ConnectionFactories,andConnections)

areallthread-safeandcanbesharedacrossseveralthreadsof

execution(andthereforecached),theSessionmustbecreatedforeach

individualthread,andshouldalwaysbeclosedattheendofitsuse.

//CreateaQueueSession

javax.jms.QueueSessionsession=



conn.createQueueSession(false,javax.jms.Session.AUTO_ACKNOWLEDG



Nowthatyou'vecreatedaSession,you'refinallyreadytocreatea

messageproduceronthequeuethatweobtainedinthefirststep:

javax.jms.QueueSendersender=session.createSender(aQueue);



Ourexampleisnearlyfinished.Wecannowcreateamessageandplace



itonaqueue.InJMS,messagescomeinseveralflavors.TextMessages

aremessageswhosebody(orpayload)isatextstring.Therearealso

ObjectMessagesthatcarryserializedJavaobjects,MapMessagesthat

carryname/valuepairs,ByteMessages,andStreamMessages.Inour

example,we'lluseaTextMessage,whichisprobablythemostcommonly

usedmessagetype:

//CreatetheTextMessage

Messagemessage=session.createTextMessage();

message.setJMSType("LogMessage");

message.setText("HelloWorld");

//Sendthemessage

sender.send(message);



InthisquickintroductiontousingJMStosendmessages,we'veomitted

alloftheexceptionprocessingthatisnecessaryinafullexample.We'll

showthatlaterinthechapter.We'vealsonotcoveredreceiving

messages,whichwe'llcoverlateraswell.However,thisshouldserveas

agoodenoughintroductiontotheconceptsthatyoucanunderstandthe

morecompleteexamplespresentedlater.



27.3Message-DrivenBeans

MDBsareadirectoutgrowthoftheJMStechnology.MDBsarestateless,

server-side,transaction-awarecomponentsforhandlingasynchronous

JMSmessages.MDBsarenewtotheEJB2.0specification.

AnMDBisaverylightweightEJBwhichsimplyprocessesmessages

deliveredbyJMS.Thecontainerhandlestransactions,security,

resources,concurrency,andmessageacknowledgement.Averynice

featureisthatanMDBcanconsumeandprocessmessages

concurrently.PreviouslyinJMSifyouneededtoprocessmessages

concurrently,youwouldhavehadtodevelopacustomframeworkto

instantiate,manage,andsynchronizeresourcesacrossthreads.MDBs

allowthebeandevelopertofocusonwhathastohappenwhena

messageisdelivered.Butmoreimportantly,MDBsallowJMSmessage

consumptiontobeincludedinatransaction.

MDBsareindeedenterprisebeanscompletewithXMLdeployment

descriptorelements.However,anMDBdoesnothavethefamiliar

componentinterfaces(Home,LocalHome,etc.).MDBshavenoneedfor

componentinterfacesbecausetheonlywayanMDBcanprocessa

messageisforthesubjectdestination(queueortopic)tohavebeen

givenamessage.MDBsonlyrespondtoasynchronousmessages,notto

clientrequests.

WhencreatinganMDB,theonlymethodwhichmustbeimplementedis

onMessage(MessageaMsg)whichiscalledwhenanasynchronous

messageisreceived.InsidetheonMessage()method,theMessage

objectcanbeexaminedtoobtainthecompletemessagedelivered.The

Messageobjectmaybeasimpletextmessage,aserializableobject,ora

MapMessage.AMapMessageisessentiallyahashtablecontainingkeys

andvalues.

WhiletheprimarypurposeofanMDBistoconsumemessages,itis

possible,andmanytimesitwillbenecessary,tosendmessagesfromthe

MDB.Hence,MDBscancontactotherEJBsusingstandardJ2EE



constructsorenqueuemessagesusingJMS.Forinstance,imaginea

simpleworkflowsituationwhereachainofasynchronouseventsneedsto

occur.OncetheMDBhashandleditsmessage,itcansendanother

asynchronousmessagetothenextdestinationintheworkflow.



27.3.1ExampleMDBinWSAD

Nowit'stimetobuildasampleMDBandtestclientinWSAD.Sincemost

clientsofanMDBwillbeaservletorsessionbean,wewilluseatest

servlettoexercisetheMDB.Wecouldhaveusedanapplicationtest

clientbutusingaservletwillallowustoshowhowtosetupresource

referencesinWSADfortheJMSresources.

Wewillperformthefollowingstepsincreatingourexample:

1. Createtheenterpriseproject

CreatetheMDB

Createatestservlet

ConfiguretheJNDInames

Testanddebug

Nowitistimetoelaborate.



27.3.1.1CreatetheEnterpriseProject

GototheJ2EEPerspectiveandcreateandenterpriseprojectby

selectingtheFile>New>EnterpriseApplicationProject.Thedialogin

Figure27.2willbedisplayed.



Figure27.2.CreateJ2EE1.3enterpriseproject.



SelecttheradiobuttonforaJ2EE1.3enterpriseapplicationprojectand

presstheNextbuttontodisplayFigure27.3.



Figure27.3.SpecifyEARmodules.



NametheprojectMDBSampleandspecifythatanEJBandWebproject

alsobecreatedforthisEAR.NametheEJBmoduleMDBSampleEJB

andnametheWebmoduleMDBSampleWeb.Sincewewillbeusinga

servletforourJMSmessagesender,wedonotneedanapplicationclient

project.PresstheFinishbuttontocreatethethreeprojects.The

NavigatorviewintheJ2EEperspectiveshouldnowresembleFigure

27.4.



Figure27.4.NavigationviewinJ2EEperspective.



NoticethattheMDBSampleenterpriseapplicationcontainstwo

modulesMDBSampleEJB.jarandMDBSampleWeb.jar.



27.3.1.2CreatetheMDB

TheMDBisverysimpletocreate.Theonlymethodthatwehaveto

implementisonMessage(MessageaMsg).Inthissample,allofthe

logicisperformedinonMessage().Thisisgenerallyabadpractice.Ina

realapplication,youshouldalwaysdelegatetoamediator,domain

object,orcallacommand.TheMDBisahandler,whichshouldrouteto

otherreusablecomponents.TocreatetheMDB,selectthe

MDBSampleEJBmoduleandthenfromtheright-click,selecttheNew>

EnterpriseBeanmenuselection.Anenterprisebeancreationdialogwill

bedisplayedasinFigure27.5.



Figure27.5.SelecttheEJBproject.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 27. Introduction to Message-Driven Beans

Tải bản đầy đủ ngay(0 tr)

×