Tải bản đầy đủ - 0 (trang)
Chapter 12. Enterprise Servlets and J2EE

Chapter 12. Enterprise Servlets and J2EE

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





JavaServletProgramming,2ndEdition>12.EnterpriseServletsandJ2EE>12.1

DistributingLoad




CONTINUE>



12.1DistributingLoad

Forhigh-trafficand/orhigh-reliabilitysites,it'softendesirabletodistributethe

site'scontentandprocessingdutiesacrossmultiplebackendservers.This

distributionallowsmultipleserverstosharetheload,increasingthenumberof

simultaneousrequeststhatcanbehandledandprovidingfailoversothesitecan

remainupevenwhenoneparticularcomponentcrashes.

Distributionisn'tappropriateforeverysite.Creatingandmaintaininga

distributedsitecanbesignificantlymorecomplicatedthandoingthesamefora

standalonesiteandcanbemorecostlyaswellintermsofload-balancing

hardwareand/orsoftwarerequirements.Distributionalsodoesn'ttendto

provideasignificantperformancebenefituntiltheserverisunderextremeload.

Whenpresentedwithaperformanceproblem,it'softeneasiestto"throw

hardwareattheproblem"byinstallingasinglehigher-endmachineratherthan

tryingtosharetheloadbetweentwounderperformingmachines.

Still,therearemanysitesthatneedtoscalebeyondthecapabilitiesofasingle

machineandthatneedalevelofreliabilitynosinglemachinecanoffer.These

arethesitesthatneedtobedistributed.

12.1.1HowtoBeDistributable

Theprogrammingrequirementsforadistributableservletaremuchstricterthan

therequirementsforanondistributableservlet.Adistributableservletmustbe

writtenfollowingcertainrulessothatdifferentinstancesoftheservletcan

executeonmultiplebackendmachines.Anyprogrammerassumptionsthat

there'sonlyoneservletinstance,oneservletcontext,oneJVM,orone

filesystemhavethepotentialtocauseseriousproblems.

Tolearnhowservletscanbedistributed,lookatEnterpriseJavaBeans(EJB)

technology,aserver-sidecomponentmodelforimplementingdistributed

businessobjectsandthetechnologythat'sattheheartofJ2EE.EJBisdesigned

fromthegroundupasdistributableobjects.AnEJBimplementsbusinesslogic



andletsthecontainer(essentiallytheserver)inwhichitrunsmanageservices

suchastransactions,persistence,concurrency,andsecurity.AnEJBmaybe

distributedacrossanumberofbackendmachinesandmaybemovedbetween

machinesatthecontainer'sdiscretion.Toenablethisdistributionmodel,EJB

mustfollowastrictspecification-definedrulesetforwhattheycanandcannot

do.[1]

[1]FormoreinformationonEnterpriseJavaBeansseehttp://java.sun.com/products/ejband



EnterpriseJavaBeansbyRichardMonson-Haefel(O'Reilly).



Servletshavenosuchspecification-definedruleset.Thisstemsfromtheir

heritageasfrontendserver-sidecomponents,usedtocommunicatewiththe

clientandcallonthedistributedEJBandnotbedistributedthemselves.

However,forhigh-trafficsitesorsitesthatneedhighreliability,servletstoo

needtobedistributed.WeexpectupcomingServletAPIversionstoincludea

tighterdefinitionfortheimplementationofdistributedservletcontainers.

Thefollowingareourownrulesofthumbforwritingservletstobedeployedin

adistributedenvironment:

Considerthatdifferentinstancesoftheservletmayexistoneachdifferent

JVMand/ormachine.Therefore,instancevariablesandstaticvariables

shouldnotbeusedtostorestate.Anystateshouldbeheldinanexternal

resourcesuchasadatabaseorEJB(theservlet'snamecanbeusedinthe

lookup).

ConsiderthatadifferentinstancesoftheServletContextmayexistoneach

differentJVMand/ormachine.Therefore,thecontextshouldnotbeused

tostoreapplicationstate.Anystateshouldbeheldinanexternalresource

suchasadatabaseorEJB(thecontext'spathcanbeusedinthelookup).

ConsiderthatanyobjectplacedintoanHttpSessionshouldbecapableof

beingmovedto(oraccessedfrom)adifferentmachine.Forexample,the

objectcanimplementjava.io.Serializable.Beawarethatbecause

sessionsmaymigrate,thesessionunbindeventmayoccuronadifferent

machinethanthesessionbindevent!

Considerthatfilesmaynotexistonallbackendmachines.Therefore,you

shouldavoidusingthejava.iopackageforfileaccessandusethe

getServletContext().getResource()mechanisminsteadormakesureall



accessedfilesarereplicatedacrossallbackendmachines.

Considerthatsynchronizationisnotglobalandworksonlyforthelocal

JVM.

Awebapplicationwhosecomponentsfollowtheserulescanbemarked

distributable,andthatmarkingallowstheservertodeploytheapplication

acrossmultiplebackendmachines.Thedistributablemarkisplacedwithinthe

web.xmldeploymentdescriptorasanemptytaglocated

betweentheapplication'sdescriptionanditscontextparameters:





AllservletsandJSPsarereadyfordistributeddeployment















Applicationsarenondistributablebydefault,toallowthecasualservlet

programmertoauthorservletswithoutworryingabouttheextrarulesfor

distributeddeployment.Markinganapplicationdistributabledoesnot

necessarilymeantheapplicationwillbesplitacrossdifferentmachines.Itonly

indicatesthecapabilityoftheapplicationtobesplit.Thinkofitasa

programmer-providedcertification.

Serversdonotenforcemostoftheprecedingrulesgivenforadistributed

application.Forexample,aservletisnotbarredfromusinginstanceandstatic

variablesnorbarredfromstoringobjectsinitsServletContext,andaservlet

maystilldirectlyaccessfilesusingthejava.iopackage.It'suptothe

programmertoensuretheseabilitiesaren'tabused.Theonlyenforcementthat

theservermayperformisthrowinganIllegalArgumentExceptionifanobject

boundtotheHttpSessiondoesnotimplementjava.io.Serializable(andeven

that'soptionalbecause,aswe'llseelater,aJ2EE-compliantservermustallow

additionaltypesofobjectstobestoredinthesession).

12.1.2ManyStylesofDistribution



Servletdistribution(oftencalledclustering)isanoptionalfeatureofaservlet

container,andservletcontainersthatdosupportclusteringarefreetodosoin

severaldifferentways.Therearefourstandardarchitectures,listedherefrom

simplesttomostadvanced.

1. Noclustering.AllservletsexecutewithinasingleJVM,andthe

markerisessentiallyignored.Thisdesignissimple,and

worksfineforastandardsite.ThestandaloneTomcatserverworksthis

way.

2. Clusteringsupport,nosessionmigration,andnosessionfailover.Servlets

inawebapplicationmarkedmayexecuteacross

multiplemachines.Nonsessionrequestsarerandomlydistributed(modulo

someweightingperhaps).Sessionrequestsare"sticky"andtiedtothe

particularbackendserveronwhichtheyfirststart.Sessiondatadoesnot

movebetweenmachines,andthishastheadvantagethatsessionsmayhold

nontransferable(non-Serializable)dataandthedisadvantagethatsessions

maynotmigratetounderutilizedserversandaservercrashmayresultin

brokensessions.ThisisthearchitectureusedbyApache/JServand

Apache/Tomcat.Sessionsaretiedtoaparticularhostthroughamechanism

wherethemod_jserv/mod_jkconnectorinApacheusesaportionofthe

sessionIDtoindicatewhichbackendJServorTomcatownsthesession.

MultipleinstancesofApachemaybeusedaswell,withthesupportof

load-balancinghardwareorsoftware.

3. Clusteringsupport,withsessionmigration,nosessionfailover.This

architectureworksthesameastheformer,exceptasessionmaymigrate

fromoneservertoanothertoimprovetheloadbalance.Toavoid

concurrencyissues,anysessionmigrationisguaranteedtooccurbetween

userrequests.TheServletSpecificationmakesthisguarantee:"Withinan

applicationthatismarkedasdistributable,allrequeststhatarepartofa

sessioncanonlybehandledonasingleVMatanyonetime."Allobjects

placedintoasessionthatmaybemigratedmustimplement

java.io.Serializableorbetransferableinsomeotherway.

4. Clusteringsupport,withsessionmigrationandwithsessionfailover.A

serverimplementingthisarchitecturehastheadditionalabilitytoduplicate

thecontentsofasessionsothecrashofanyindividualcomponentdoesnot

necessarilybreakauser'ssession.Thechallengewiththisarchitectureis



coordinatingefficientandeffectiveinformationflow.Mosthigh-end

serversfollowthisarchitecture.

Thedetailsonhowtoimplementclusteringvarybyserverandareapointon

whichservervendorsactivelycompete.Looktoyourserver'sdocumentationfor

detailsonwhatlevelofclusteringitsupports.Anotherusefulfeaturetowatch

forissessionpersistence,thebackgroundsavingofsessioninformationtodisk

ordatabase,whichallowstheinformationtosurviveserverrestartsandcrashes.

Lastupdatedon3/20/2003

JavaServletProgramming,2ndEdition,©2001O'Reilly






CONTINUE>







JavaServletProgramming,2ndEdition>12.EnterpriseServletsandJ2EE>12.2

IntegratingwithJ2EE




CONTINUE>



12.2IntegratingwithJ2EE

Throughouttherestofthisbook,servletshavebeenusedasastandalonetechnology

builtuponthestandardJavabase.Servletshaveanotherlife,however,wheretheyact

asanintegralpieceofwhat'sknownasJava2,EnterpriseEdition,orJ2EEfor

short.[2]J2EE1.2collectstogetherseveralserver-sideAPIsincludingServletAPI

2.2,JSP1.1,EJB,JavaMail,theJavaMessagingService(JMS),JavaTransactions(

JTA),CORBA,JDBC,theJavaAPIforXMLParsing(JAXP),andtheJavaNaming

andDirectoryInterface(JNDI).J2EEmakesthewholegreaterthanthesumofits

partsbydefininghowthesetechnologiescaninteroperateandmakeuseofone

another,andprovidingcertificationthatcertainapplicationserversareJ2EE

compliant,meaningtheyprovidealltherequiredservicesaswellastheextra

connectionglue.

[2]MostpronounceJ2EEasJ-2-E-EbutthosewhoknowitbestatSunjustsay"jah-too-ee."



12.2.1J2EEDivisionofLabor

J2EEbreaksenterpriseapplicationdevelopmentintosixdistinctroles.Ofcourse,an

individualmayparticipateinmorethanoneroleandmultipleindividualsmaywork

togetherinagivenrole.

J2EEproductprovider

Theoperatingsystemvendor,databasesystemvendor,applicationserver

vendor,and/orwebservervendor.Theproductproviderprovidesan

implementationoftheJ2EEAPIsandtoolsforapplicationdeploymentand

management.

Applicationcomponentprovider

Theauthoroftheapplication'sservlets,EJB,andothercodeaswellasgeneral

contentsuchasHTML.(Inotherwords,you.)



Applicationassembler

Takestheapplication'scomponentsand(usingtoolsfromtheproductprovider)

placestheminaformappropriatefordeployment.Aspartofthistheassembler

describestheexternaldependenciesoftheapplicationthatmaychangefrom

deploymenttodeployment,likedatabaseoruserlogininformation.

Deployer

Takestheoutputoftheassemblerand(usingtoolsfromtheproductprovider)

installs,configures,andexecutestheapplication.Theconfigurationtask

requiressatisfyingtheexternaldependenciesoutlinedbytheassembler.

Systemadministrator

Configuresandadministersthenetworkinfrastructuretokeeptheapplication

alive.

Toolprovider

CreatestoolstosupportJ2EEdevelopment,beyondthoseprovidedbythe

productprovider.

Thedivisionoflaborbetweencomponentprovider,assembler,anddeployerhasan

impactonhowwe(asservletprogrammersinthecontentproviderrole)behave.

Specifically,weshoulddesignourcodetomakeexternaldependenciesclearforthe

assembler,andfurthermoreweshouldusemechanismsthatallowthedeployerto

satisfythesedependencieswithoutmodifyingthefilesreceivedfromtheassembler.

Thatmeansnodeployereditstotheweb.xmlfile!Whynot?BecauseJ2EE

applicationsareassembledintoEnterpriseArchive(.ear)filesofwhichacontained

webapplication'sweb.xmlfileisbutoneuneditablepart.

Thissoundsmoredifficultthanitactuallyis.J2EEprovidesastandardmechanismto

achievethisabstractionusingJNDIandafewspecialtagsintheweb.xml

deploymentdescriptor.JNDIisanobjectlookupmechanism,awaytobindobjects

undercertainpathsandlocatethemlaterusingthatpath.Youcanthinkofitlikean

RMIregistry,exceptit'smoregeneralwithsupportforaccessingarangeofservices

includingLDAPandNIS(andeven,infact,theRMIregistry!).Anassembler

declaresexternaldependencieswithintheweb.xmlusingspecialtags,adeployer

satisfiesthesedependenciesusingserver-specifictools,andatruntimeourJavacode



usestheJNDIAPItoaccesstheexternalresourceskindlyplacedtherebytheJ2EEcompliantserver.Allgoalsaresatisfied:ourJavacoderemainsportablebetween

J2EE-compliantservers,andthedeployercansatisfythecode'sexternal

dependencieswithoutmodifyingthefilesreceivedfromtheassembler.There'seven

enoughflexibilityleftoverforservervendorstocompeteonimplementationsofthe

standard.

12.2.2EnvironmentEntries

Contextinitparametersserveausefulpurposewithservlets,butthere'saproblem

withcontextinitparametersintheJ2EEmodel:anychangetoaparametervalue

requiresamodificationtotheweb.xmlfile.Forparametervaluesthatmayneedto

changeduringdeployment,it'sbettertouseenvironmententriesinstead,asindicated

bythetag.Thetagmaycontaina,,,and.Thefollowing

specifieswhethertheapplicationshouldenablesendingofPINcodesbymail:



Sendpincodebymail

mailPincode

false

java.lang.Boolean





Theexplainstothedeployerthepurposeofthisentry.It'soptionalbut

agoodideatoprovide.TheisusedbyJavacodeaspartofthe

JNDIlookup.Thedefinesthedefaultvaluetobepresentedtothe

deployer.It'soptional,butnotspecifyingavaluerequiresthedeployertoprovide

one.Therepresentsthefullyqualifiedclassname(FQCN)ofthe

entry.ThetypemaybeaString,Byte,Short,Integer,Long,Boolean,Double,or

Float(allwiththeirfulljava.langqualification).Thetypehelpsthedeployerknow

what'sexpected.Ifyou'refamiliarwiththeEJBdeploymentdescriptor,thesetags

maylookfamiliar;theyhavethesamenamesandsemanticsinEJBaswell.

JavacodecanretrievethevaluesusingJNDI:

ContextinitCtx=newInitialContext();

BooleanmailPincode=(Boolean)initCtx.lookup("java:comp/env/mailPincode");



Allentriesareplacedbytheserverintothejava:comp/envcontext.Ifyou'renewto

JNDI,youcanthinkofthisasaURLbaseorfilesystemdirectory.The



java:comp/envcontextisread-onlyanduniqueperwebapplication,soiftwo



differentwebapplicationsdefinethesameenvironmententry,theentriesdonot

collide.Thecontextabbreviations,bytheway,standforcomponentenvironment.

Example12-1showsaservletthatdisplaysallitsenvironmententries,usingthe

JNDIAPItobrowsethejava:comp/envcontext.

Example12-1.Snoopingthejava:comp/envContext

importjava.io.*;

importjava.util.*;

importjavax.servlet.*;

importjavax.servlet.http.*;

importjavax.naming.*;

publicclassEnvEntrySnoopextendsHttpServlet{

publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)

throwsServletException,IOException{

res.setContentType("text/plain");

PrintWriterout=res.getWriter();

try{

ContextinitCtx=newInitialContext();

NamingEnumerationenum=initCtx.listBindings("java:comp/env");

//We'reusingJDK1.2methods;that'sOKsinceJ2EErequiresJDK1.2

while(enum.hasMore()){

Bindingbinding=(Binding)enum.next();

out.println("Name:"+binding.getName());

out.println("Type:"+binding.getClassName());

out.println("Value:"+binding.getObject());

out.println();

}

}

catch(NamingExceptione){

e.printStackTrace(out);

}

}

}



Assumingthepreviousweb.xmlentry,theservletwouldgenerate:

Name:mailPincode

Type:java.lang.Boolean

Value:false



Remember,aserverthatdoesnotsupportJ2EEisnotrequiredtosupportthesetags

oranyofthetagswetalkaboutinthissection.

12.2.3ReferencestoEJBComponents

WhentheenvironmententryobjectisanEJBcomponent,there'saspecial

tagthatmustbeused.ItprovidesawayforservletstogetahandletoanEJBusing

anabstractname.Thedeployerensurestheavailabilityofanappropriatebeanat

runtimebasedontheconstraintsgivenbythetag.Thetagmaycontaina

,,,,,and

Here'satypical:



Cruiseshipcabin

ejb/CabinHome

Entity

com.titan.cabin.CabinHome

com.titan.cabin.Cabin





ThesetagsalsohavesimilarcounterpartsinEJB,andinfactthisexampleis

borrowedfromthebookEnterpriseJavaBeansbyRichardMonson-Haefel

(O'Reilly).Thesupportsthedeployerandisoptionalbut

recommended.ThedictatestheJNDIlookupname.It's

recommended(butnotrequired)thatthenamebeplacedwithintheejb/subcontext,

makingthefullpathtothebeanjava:comp/env/ejb/CabinHome.The

musthaveavalueofeitherEntityorSession,thetwotypesofEJBcomponents.

Finally,theelementspecifiesthefullyqualifiedclassnameoftheEJB'shome

interface,whiletheelementspecifiestheFQCNoftheEJB'sremote

interface.

[3]TheServletAPI2.2Specificationstates,"Theejb-ref-typeelementcontainstheexpectedJava



classtypeofthereferencedEJB."Thisisaconfirmedmistake.Theactualpurposeisasstatedhere.



AservletwouldobtainareferencetotheCabinbeanwiththefollowingcode:

InitialContextinitCtx=newInitialContext();

Objectref=initCtx.lookup("java:comp/env/ejb/CabinHome");

CabinHomehome=

(CabinHome)PortableRemoteObject.narrow(ref,CabinHome.class);



Iftheassemblerwritingtheweb.xmlfilehasaspecificEJBcomponentinmindfor



anEJBreference,thatinformationcanbeconveyedtothedeployerwiththeaddition

oftheoptionalelement.Theelementshouldrefertothe

ofanEJBcomponentregisteredinanEJBdeploymentdescriptorwithin

thesameJ2EEapplication.Thedeployerhastheoptiontousethesuggestionor

overrideit.Here'sanupdatedweb.xmlentry:



Cruiseshipcabin

ejb/CabinHome

Entity

com.titan.cabin.CabinHome

com.titan.cabin.Cabin

CabinBean





12.2.4ReferencestoExternalResourceFactories

Finally,forthosetimeswhentheenvironmententryisaresourcefactory,there'sa

tagtouse.Afactoryisanobjectthatcreatesotherobjectson

demand.Aresourcefactorycreatesresourceobjects,suchasdatabaseconnectionsor

messagequeues.

Thetagmaycontaina,,

and.Here'satypical:



Primarydatabase

jdbc/primaryDB

javax.sql.DataSource

CONTAINER





Theagainsupportsthedeployerandisoptionalbutrecommended.

ThedictatestheJNDIlookupname.It'srecommendedbutnot

requiredtoplacetheresourcefactoriesunderasubcontextthatdescribestheresource

type:

jdbc/foraJDBCjavax.sql.DataSourcefactory

jms/foraJMSjavax.jms.QueueConnectionFactoryor

javax.jms.TopicConnectionFactory

mail/foraJavaMailjavax.mail.Sessionfactory



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

Chapter 12. Enterprise Servlets and J2EE

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

×