Tải bản đầy đủ - 0 (trang)
2 Why Aren't HTML, Servlets, and JSPs Enough?

2 Why Aren't HTML, Servlets, and JSPs Enough?

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

18.3ObjectDistribution

ThefirstoftheproblemsaddressedbyEJBsisthatobjectsinan

enterprise-scalablesystemneedtobedistributed.Inshort,thismeans

thatthepartsofyourprogramshouldbeabletobedeployedtoasmany

differentphysicalmachinesandinasmanyseparateoperatingsystem

processesasappropriatetoachievetheperformance,scalability,

availability,andreliabilitygoalsofyoursystem.

Anotherreasontodistributeobjectsistotakeasystemthatislogically

layeredandimplementthelayeringasphysicaltiersinthiswayasetof

distributedobjectscanbeaccessedfrommultiple,independently

developedsystemssolongasthoseobjectsprovideasingle,common,

networkedAPIforthenewsystemstobuildon.

Inthepreviouschapters,applicationshandleddistributionbyeitherHTTP

oraremoteconnectiontoadatabasemanagementsystem.HTTP

providesaverysimple,statelessmeansofaccessingcoarse-grained

distributedresources.ThisworkswellforHTMLpagesandother

document-centeredresources,butitdoesnotsupporttherichsemantics

thatareoftenrequiredfordistributedbusinessapplications.

HTTPisoneofanumberofdistributiontechnologiestoday,butinthe

Javaworld,twotechnologiesstandoutasespeciallywidespreadand

important:OMGCORBAobjectdistributionmodelandSunJavaRemote

MethodInvocation(RMI)protocol.

Notcoincidentally,theyarethetwothatformthecoreofthedistribution

solutionforEJBs.SincethisbookisnotabouteitherCORBAorRMI,we

referthereadertootherworkslike[Orfali]thatprovideamoredetailed

overviewofthesetechnologies.

Wedoneedtolookatacoupleoftheprosandconsofeachtechnology

tounderstandwhytheEJBmodelhasevolvedasithas.Alongtheway,

wewillpointoutareasthatwewillcovermorein-depthaswebeginto

examinetheEJBdistributionmodel.



18.3.1AQuickOverviewofCORBA

CORBAwasdevelopedbyaconsortiumofcompaniesduringtheearly

1990stoprovideacommonlanguageandvendor-neutralstandardfor

objectdistribution.CORBAhasbeenwellacceptedsinceitsinception,

withanumberofproductsandvendorssupportingtheCORBAstandard,

andalonghistoryofsuccessfulprojectsdevelopedusingit.

TheheartofCORBAistheideaofaspecial-purposepieceofsoftware,

anORBthatfacilitatescommunicationbetweenobjectspaces.The

CORBAmodelrequiresanORBonbothendsofthedistributedsystem.

TheORBisresponsibleforhandlingthemarshalingofparametersfrom

outgoingmethodinvocationstoaCORBAproxy,andresponsiblefor

receivingmessagesontheotherendofaconversationandturningthem

intolocalmessagestoaCORBAstubthatcanthenactonthereceived

messageandreturnaresponsetothecallingobject.

TherearetwomoremajorpiecesoftheCORBAmodel:IDL,the

languageinwhichCORBAinterfacesaredefined;andCORBAServices,

whichprovidestandardwaysforCORBAobjectstointeract.CORBA

Servicesincludethingslikenaming,transactions,etc.,whichwewillsee

aremajorpartsofbuildingadistributedsystem.Bydefault,CORBAuses

IIOPforlow-levelcommunicationbetweenORBs.

CORBAisarobustandcompletesetoftechnologiesthatareboth

matureandwellunderstood.SomeoftheadvantagesofCORBAare:

Itisastandardinterface.Thismakesitpossibleformultiplevendors

toimplementtheirownproductsbasedonthestandard,andmakes

itpossiblefortheseproductstointeroperate.

Itiscomputerlanguageneutral.CORBAclientsandserverscanbe

writteninavarietyofcomputerlanguages,includingJava,C++,C,

Smalltalk,andAda.Theonlyrequirementisthattheremote

interfacesforCORBA-distributedobjectsbewritteninCORBAIDL,

whichistranslatedintoclassesinthetargetimplementation



languagethroughapostprocessor(aCORBAcompiler).

Itprovidesaspecificationofcommonservicesthatarerequiredby

mostdistributedapplications,simplifyingapplicationdevelopmentby

eliminatingtheneedforeachprogramtorecreateitsown

implementation.

However,thetechnologycannotbeallthingstoallpeople.Two

disadvantagestousingCORBAtobuilddistributedsystemsinJavaare:

Developersmustusetwolanguages:IDLandJava

Veryfewvendorsimplementalloftheoptionalserviceslikesecurity

andtransactions,makingitdifficulttobuyacompleteinfrastructure.

Asaresult,CORBAhasnotmadethegreatinroadsintocorporate

InformationSystems(IS)departmentsthatitsoriginatorshadhoped.

Instead,developersstartedtolookforsimplersolutions,butsolutions

thatperhapswerenotasflexibleandpowerful.Outofthatsearchgrew

theinterestinJavaRMI.



18.3.2ABriefOverviewandHistoryofRMI

JavaRMIisastandardpartoftheSunJDK1.1andtheJava2platform.

RMIisanall-Javadistributionsolution.Itsprimaryadvantagesarethatit

featuresaverysimpleprogrammingmodelthatdoesnotrequire

programmingintwolanguages(JavaandIDL)likeCORBA,anddoesnot

requireyoutopurchaseadditionalORBandCORBAtools.

RMI'sprogrammingmodelisverysimple.Ithasthenotionofaremote

objectandaremoteinterfaceasitstwoprimaryconstituents.Aremote

objectisanobjectwhosemethodscanbeinvokedfromanotherJVM,

potentiallyonadifferenthost.Aremoteobjectisdescribedbyoneor

moreremoteinterfaces,whichareJavainterfacesthatdeclarethe



methodsoftheremoteobject.RMIistheactionofinvokingamethodofa

remoteinterfaceonaremoteobject.

RemoteinterfacesarestandardJavainterfacesthatextend

java.rmi.Remote.

Remoteobjectscanbeanyclassofobjectsthatimplementaremote

interface,althoughmoreoftenthannotremoteobjectsextend

java.rmi.server.UnicastRemoteObject.

AnadvancedfeatureinRMIthatisnotinCORBAisdistributedgarbage

collection.AfeaturethatisnotdirectlysupportedinCORBAisthenotion

ofpass-by-valueobjects.InRMI,anyJavaobjectthatimplements

java.io.Serializablecanbepassedasamethodparametertoa

remoteobject,anditwillbeserializedontheclientend,anddeserialized

ontheserverend,allowingtheservertooperateonalocalcopyofthe

parameter.[1]

[1]Javaserializationisatechnologythatisoftenpoorlyunderstood.Foranexplanationof



serialization,see[Horstmann]



WhileRMIisverypowerful,itdoesn'tsupportmultiplelanguages,nor

doesitsupportalloftheservicesthatCORBAsupports.Forinstance,

RMIincludesanamingservice,butnototherCORBAServiceslike

transactionsorpersistence.

Also,thereisaperceivedlackofsecurityinsystemsusingRMI.While

RMIincludesasecuritymanagerthatallowsappletstouseRMI,itslack

ofauthenticationandothersecurityprotocols,andthelackofsupportfor

RMIincorporatefirewallsystemshavemadeitsintroductionmore

problematicthanthatofCORBA,whichdoesnothavetheseperceived

problems.Thesereasonsleadtothecombinationofthetwotechnologies

(RMIoverIIOP).

RMIoverIIOPcombinesthebestfeaturesofRMIwiththoseofCORBA.

LikeRMI,RMIoverIIOPallowsdeveloperstodeveloppurelyinJava.

DevelopersdonothavetodevelopinbothJavaandIDL.LikeRMI,RMI

overIIOPallowsdeveloperstowriteclassesthatpassanyserializable



Javaobjectasremotemethodargumentsorreturnvalues.However,RMI

overIIOPusesIIOPasitscommunicationprotocol,soitisinteroperable

withotherCORBAapplications.Thecombinationofthesetwo

technologiesformsanunbeatablecombinationofpowerandeaseofuse.



18.3.3SomeoftheRemainingHoles

So,RMImakesdistributedprogrammingamuchsimplerpropositionfor

Javaprogrammers,andRMIoverIIOPgivesprogrammerstheeaseof

useofRMIcombinedwiththeinteroperabilityofCORBA.However,there

arestillmanyhardproblemsleftinbuildingdistributedsystems.In

particular,RMIdidnotincludedirectsupportforacommondistribution

idiomthathadinitiallyemergedtocircumventadrawbackforCORBA.

OneoftheCORBAServicesthathadbeenproposed,partiallytodeal

withthefactthatCORBAhadnofacilitieslikedistributedgarbage

collection,wastheCORBALifecycleService.Attheheartofthisservice

specificationwastheideaofafactory[2]objectthatservedasasourceof

otherdistributedobjects.Thefactorycreatedobjectsandretrieved

existinginstanceswhereappropriate.MostCORBAsystemshadevolved

intousingthisidiom,evenwheretheLifecycleServicewasnotfully

implemented.

[2]Afactoryobject'sjobistocreateotherobjects.TheFactoryMethodandAbstract



FactoryDesignPatterns[Gamma]arespecializationsofthismoregeneralpattern.



18.3.4WhereThisLeadsUs

Luckily,developerscannowtakeadvantageofbothoftheseuseful

piecesoftechnologythathaveaddressedthepriorissuesofCORBAand

RMI.EJBsuseRMIoverIIOPastheirbasedistributiontechnology.

Likewise,inJ2EE,theEJBhomeinterfacesplaytherolefactoryobjects,

incorporatingobjectlifecyclemanagement.Wewillexaminetheseissues

inmoredepthwhenweintroducetheEJBprogrammingmodelin

Chapter19.



18.4IntegrationStylesandMessaging

Sofar,we'veconsideredtheissueofobjectdistribution,andhaveshown

howthemostcommonmechanismsinJavahavesolvedthisproblem.

However,aswediscussedatthebeginningofthechapter,thereare

manywaystohandleprogram-to-programcommunicationinJava.The

generalproblemofprogram-to-programcommunicationhasbeena

constantandongoingsourceofresearch,development,andheartache

almostsincethedawnofthecomputerage.Inparticular,fivedifferent

waysofprogramintegrationhaverisentotheforefrontasthemost

commonlyimplementedsolutionstothisproblem.Let'sexaminethemso

thatwecanunderstandthemostcommon,andattractive,alternativesto

objectdistributioninparticularsituations.

FiletransferThiswastheoriginalmeansofprogram-to-program

communication,andisstillthebasisofmanymainframesystems.In

it,eachprogramworksonaphysicalfile(stored,perhaps,onahard

disk,atapedrive,orastackofpunchedcards)andthenanother

programwilltakethatfileasitsinputandproduceanewfile,or

modifythefileifthestoragemediumallowsit.Whilethishasproven

effectiveforsolvingmanyproblems,issuesoflatencyandresource

contentionhaveusuallymadeitunattractivefortoday'shigh-speed,

high-volumeapplications.

ShareddatabaseAnotherpopularmechanismderivedfromthefile

transfermechanismistheshareddatabasesystem.Inthissolution,

databasesoftwarehandlessomeoftheresourcecontentionissues

byprovidingmechanismsforlockingandunlockingthedata

appropriately,andalsoprovidesstandardmechanismsforcreating,

deleting,searching,andupdatinginformation.However,thelatency

issueremainseveninthissolution:Beforeoneprogramcanuse

information,itmustbewrittentoadatabase(aphysicalfile)bythe

otherprogram.ShareddatabasesarestillakeypartoftheJ2EE

standard.Itisonlythroughshareddatabasesthatwecanachieve

thescalabilityofJ2EEbyallowingentitybeansindifferentJVMs



(perhapsinaclonedenvironmentsuchasispossibleinWASND)to

handletransactionsagainstthesametablessimultaneously.

RawdatatransferInthisscheme,differentprogramsusea

mechanismlikeanetworkdatatransferprotocol(suchasTCP/IP

sockets)oraphysicaltransfermechanism(e.g.,sharedmemory)to

communicateinformationbetweendifferentprograms.Thedrawback

ofthispopularsolutionisthatitrequiressynchronous

communicationeachprogrammustwaitontheothertocompleteits

requestbeforeprocessingaresponse.Whileitispossibleto

temporarilydisconnectthesystems,thisinvolvesaddingsignificant

complexitytotheoverallsystem,andleadstoprogrammingissues

thatfewprogrammersarecompetenttodealwith.Forexample,itis

uptotheprogrammertodecidehowtoguaranteethatamessageis

properlysentandreceived;thedevelopermustprovideretrylogicto

handleallthecaseswherethenetworklinkissevered,orthe

requestorresponsewaslostintransmission.Youmightthinkthat

rawdatatransferisnotapartoftheJ2EEstandard,especiallysince

theEJBspecificationspecificallyrestrictstheuseofJavasockets

withinEJBs.However,ifyouconsiderthattheHTTPprotocolfitsthis

definition,youcanseethatthisapproachisstillakeypartofJ2EE.

RPCRemoteProcedureCallisawayofreducingthecomplexityof

therawdatatransferapproachbywrappingthenetworkprotocols

withinalayerofcodelibrariessoitappearstothecallingandcalled

programsthatanormalprocedurecallhadtakenplace.RPCis

extremelypopular,andisthebasisofmodernsystemslikeCORBA,

RMI,andEJB.However,thebasicissuesofsynchronicityand

guaranteeddeliverystillremain,whichleadustotheneedforyet

anotherdatatransfermechanism.

MessagingMessagingisameansofprovidinghigh-speed,

asynchronous,program-to-programcommunicationwithguaranteed

delivery.Thisparticularsolutionisoftenimplementedasalayerof

softwarecalledMessage-OrientedMiddleware(MOM).



Ascomparedtotheotherfourcommunicationmechanisms,relativelyfew

developershavehadexposuretomessagingandMOMs,anddevelopers

ingeneralarenotfamiliarwiththeidiomsandpeculiaritiesofthis

communication'splatform.Asaresult,wehaveseenmanyprogrammers

trytousemessaginginaninappropriateway,ortodevelopsystemsthat

donottakeadvantageofthecapabilitiesandstrengthsofmessaging.



18.4.1JMSandMOMs

Asimplewaytounderstandwhatamessagingsystemdoesisto

considervoicemail(aswellasansweringmachines)forphonecalls.

Beforevoicemail,whensomeonecalled,ifthereceivercouldnotanswer,

thecallerhungupandcalledbacklatertoseeifthereceiverwould

answer.Withvoicemail,whenthereceiverdoesnotanswer,thecaller

canleaveamessage;later,thereceiver(athisconvenience)canlistento

themessagesqueuedinhismailbox.Voicemailenablesthecallerto

leaveamessagenowsothatthereceivercanlistentoitlater,whichis

oftenaloteasierthantryingtogetthecallerandthereceiveronthe

phoneatthesametime.Voicemailbundles(atleastpartof)aphonecall

intoamessageandqueuesitforlater;thisisessentiallyhowmessaging

works.

Inenterprisecomputing,messagingmakescommunicationbetween

processesreliable,evenwhentheprocessesandtheconnection

betweenthemarenot.

J2EEdefinesastandardAPIformessaging.ThisistheJMS.Therearea

numberofproductsavailableforembeddingmessagingintoandbetween

applications.Oneoftheoldestandbest-knownmessagingproductsis

IBM'sWebSphereMQ.WebSphereMQimplementstheJMSAPI.WAS

includesalimitedversionofMQSeries,calledWebSphereEmbedded

Messaging,thatallowsWebSphereapplicationserverstocommunicate

withotherWebSphereapplicationservers,andalsoallowsJava

applicationclientstocommunicatewithWebSphereservers.However,

WebSphereEmbeddedMessagingdoesnotsupportconnectiontoother

programs,suchaslegacysystems.Forthat,youshouldusethe



WebSphereMQproduct,whichisfullycompatiblewithWAS.

BesidesWebSphereMQ,manyotherproductsimplementtheJMSAPI,

anditispossibletousetheseproductswithWAS,butthedetailsof

managingthatintegrationarebeyondthescopeofthisbook.However,

wewilldiscusshowWebSphereEJBsinteractwiththeJMSmessaging

APIinChapter27andshowyouhowtotakeadvantageofasynchronous

communicationwithEJBs.



18.5ObjectPersistence

OfalloftheproblemsofOOP,fewhavegeneratedasmuchinterest,or

asmuchconfusion,astheproblemofobjectpersistence.Whenreduced

toitsbareessentials,objectpersistenceisnotdifficultto

understandmakinganobjectpersistentmeansitsstate(thevaluesofits

variables)canbepreservedacrossmultipleinvocationsofaprogramthat

referencesthatobject.Thiscanbeaccomplishedinanynumberofways,

theeasiestofwhichforJavaprogrammersisprobablytheJava

serializationmechanismthatispartofthebasicJDK.

It'snotpersistencepersethatgivesprogrammersandarchitects

nightmares.Theproblemisnotthatpeoplewantobjectstobepersistent,

butthattheywanttostoretheinformationintheobjectsinaparticular

formatandaccessitinacontrolledmanner.Inmostcases,thisformatis

arelationaldatabase(RDB).Unfortunately,thereisaseriousimpedance

mismatchbetweenobjectsandRDBs.

Therelational(table)modelisasimplemodel,builtuponasound

mathematicalfoundationthathasbeenitskeystrength.Itisatechnology

thathasbeenusedverysuccessfullyforanumberofyearsandis

consequentlywellunderstood.Sincenewapplicationsareseldombuiltin

avacuum,relationaltechnologyiscommonlyusedinnewapplicationsfor

thefollowingreasons:

Informationoftenexistsinlegacydatabasesthatmustbeusedby

newsystems.

RDBshavestrongqueryandreport-writingcapabilities.Eveninthe

bravenewworldofWebinterfaces,peoplestillwanttoseepaper

reports.

Relationaltechnologyprovidesbuilt-indataintegrityconstraintsin

theformofdatabasetransactionsandintegrityrules.



Therearewell-knownproceduresforbackingupandrestoring

databaseaftercatastrophicfailures.Thislevelofsafetyprovides

comfortandpeaceofmindtothecustomersthatpayfornew

systemsdevelopment.

Thedrawbacksofusingarelationaldatabasewithanobjectsystemare:

RDBshavelimitedmodelingcapabilities.Behavior,object

containment,andinheritancearenoteasytodefineinanRDBwhen

comparedtoJavaoranobjectdatabase.

ThereisnowayofrepresentingtrueJavaobjectidentityinanRDB.

WhenprogramminginanOOlanguagelikeJava,youmustinteract

withanobjectthatcontainsacopyofthepersistentdata.Thereare

alwaystwospacesatworkinaproblem,thedataspaceinthe

relationaldatabaseandtheobjectspaceinJava.Keepingthesetwo

spacesinsyncisoneoftheprimaryproblemspersistence

implementationsmustaddress.

ThereisasemanticmismatchbetweenJavaandSQL.SQLdata

typesdonotmatchJavadatatypes,leadingtoconversionproblems.

Inmanycases,upto50percentofapplicationcodebulkisdevotedto

themechanicsofconnectingapplicationobjectswiththerelational

database.AswesawinChapters8and16,itrequiresconsiderablecare

anddiligencetoensureagooddesignandimplementationwhen

combiningthetwoarchitectures.LuckilyforJavaprogrammers,many

commercialpersistenceframeworkshaveevolvedtofillthegapand

provideamappingbetweenanobjectmodelandarelationaldatabase

thataddressthepreviousissues.Thedisadvantageisthateachvendor's

APIisproprietary,andthereisnostandardizationofthecapabilitiesof

thesesolutions.However,aswewillsee,eventhisisnotthewholestory.

J2EEcontainer-managedentitybeanscanhandlepersistenceforyour

applicationsinastandardway.WewillexamineWebSphere'ssupportfor

CMPindepth,anddemonstratehowitprovidesflexible,robustobject



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

2 Why Aren't HTML, Servlets, and JSPs Enough?

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

×