1 Star 0 Fork 0

火龙战士 / zhengweishan

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
atom.xml 353.13 KB
一键复制 编辑 原始数据 按行查看 历史
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>迷失的男孩</title>
<subtitle>个人博客</subtitle>
<link href="/atom.xml" rel="self"/>
<link href="http://zhengweishan.oschina.io/"/>
<updated>2017-03-27T10:19:12.313Z</updated>
<id>http://zhengweishan.oschina.io/</id>
<author>
<name>郑伟山</name>
<email>wesley5201314@live.com</email>
</author>
<generator uri="http://hexo.io/">Hexo</generator>
<entry>
<title>java并发包里的CountDownLatch的用法</title>
<link href="http://zhengweishan.oschina.io/2017/03/27/CountDownLatch/"/>
<id>http://zhengweishan.oschina.io/2017/03/27/CountDownLatch/</id>
<published>2017-03-26T16:00:00.000Z</published>
<updated>2017-03-27T10:19:12.313Z</updated>
<content type="html"><![CDATA[<h2 id="CountDownLatch"><a href="#CountDownLatch" class="headerlink" title="CountDownLatch:"></a>CountDownLatch:</h2><p>官方的解释为:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。</p>
<p>我们现在就把它理解为倒数计数器,什么是倒数计数器呢,通俗的理解就是这个计数器事先有一个初始计数,在这个计数减到0之前,所有的线程等待。</p>
<p>最近公司有出去旅游,一个业务场景浮现在脑海:部门一共十个人出去旅游,必须10个人上车之后大巴才能开车,下面就来模拟这个上车的过程。<br><a id="more"></a></p>
<h2 id="模拟上车过程:"><a href="#模拟上车过程:" class="headerlink" title="模拟上车过程:"></a>模拟上车过程:</h2><p>首先创建人这个实体:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> java.util.concurrent.TimeUnit;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</div><div class="line"> </div><div class="line"> </div><div class="line"> <span class="keyword">private</span> Car car;</div><div class="line"> </div><div class="line"> <span class="keyword">private</span> String name;</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span> </span>&#123;</div><div class="line"> <span class="keyword">super</span>();</div><div class="line"> &#125;</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">(Car car,String name)</span> </span>&#123;</div><div class="line"> <span class="keyword">this</span>.car = car;</div><div class="line"> <span class="keyword">this</span>.name = name;</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line"> <span class="comment">// TODO Auto-generated method stub</span></div><div class="line"> <span class="keyword">try</span> &#123;</div><div class="line"> TimeUnit.SECONDS.sleep((<span class="keyword">long</span>)(Math.random()*<span class="number">10</span>));</div><div class="line"> &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line"> <span class="comment">// TODO Auto-generated catch block</span></div><div class="line"> e.printStackTrace();</div><div class="line"> &#125;</div><div class="line"> car.getton(name);</div><div class="line"> &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后在创建一个大巴车:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> java.util.concurrent.CountDownLatch;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Car</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</div><div class="line"></div><div class="line"> <span class="keyword">private</span> CountDownLatch countDownLatch;</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">()</span> </span>&#123;</div><div class="line"> <span class="keyword">super</span>();</div><div class="line"> &#125;</div><div class="line"> </div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">(<span class="keyword">int</span> count)</span> </span>&#123;</div><div class="line"> <span class="keyword">this</span>.countDownLatch = <span class="keyword">new</span> CountDownLatch(count);</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line"> System.out.println(<span class="string">"一共需要上车屌丝数:"</span>+countDownLatch.getCount());</div><div class="line"> </div><div class="line"> <span class="keyword">try</span> &#123;</div><div class="line"> countDownLatch.await();</div><div class="line"> System.out.println(<span class="string">"屌丝全部上车了---&gt;&gt;&gt;老司机准备开车了。。。。"</span>);</div><div class="line"> &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line"> <span class="comment">// TODO Auto-generated catch block</span></div><div class="line"> e.printStackTrace();</div><div class="line"> &#125;</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getton</span><span class="params">(String name)</span> </span>&#123;</div><div class="line"> System.err.println(name+<span class="string">"上车"</span>);</div><div class="line"> countDownLatch.countDown();</div><div class="line"> System.err.println(<span class="string">"还剩下"</span>+countDownLatch.getCount()+<span class="string">"个屌丝没有上车"</span>);</div><div class="line"> &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>测试类:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line"> </div><div class="line"> Car c = <span class="keyword">new</span> Car(<span class="number">10</span>);</div><div class="line"> Thread thread = <span class="keyword">new</span> Thread(c);</div><div class="line"> thread.start();</div><div class="line"> </div><div class="line"> <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=<span class="number">10</span>;i++)&#123;</div><div class="line"> Person p = <span class="keyword">new</span> Person(c, <span class="string">"屌丝"</span>+i);</div><div class="line"> Thread t = <span class="keyword">new</span> Thread(p);</div><div class="line"> t.start();</div><div class="line"> &#125;</div><div class="line"></div><div class="line"> &#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>执行结果:</p>
<p><img src="http://i.imgur.com/RVZxszU.png" alt=""></p>
<h2 id="原理分析:"><a href="#原理分析:" class="headerlink" title="原理分析:"></a>原理分析:</h2><p>当创建CountDownLatch对象时,对象使用构造函数来初始化内部计数器。</p>
<pre><code>CountDownLatch类只提供了一个构造器:public CountDownLatch(intcount) { };//参数count为计数值
</code></pre><p>每次调用countDown()方法,对象内部计数器减一。当内部计数器达到0时,CountDownLatch对象唤醒全部使用await()方法睡眠的线程。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结:"></a>总结:</h2><p>CountDownLatch对象的内部计数器的值初始化之后是不能修改的,唯一可以修改的方式就是调用countDown()方法,当计数器为0时,await()方法会立即返回,任何方法的调用都是无效的,如果想再次使用同步,必须重新初始化。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;CountDownLatch&quot;&gt;&lt;a href=&quot;#CountDownLatch&quot; class=&quot;headerlink&quot; title=&quot;CountDownLatch:&quot;&gt;&lt;/a&gt;CountDownLatch:&lt;/h2&gt;&lt;p&gt;官方的解释为:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。&lt;/p&gt;
&lt;p&gt;我们现在就把它理解为倒数计数器,什么是倒数计数器呢,通俗的理解就是这个计数器事先有一个初始计数,在这个计数减到0之前,所有的线程等待。&lt;/p&gt;
&lt;p&gt;最近公司有出去旅游,一个业务场景浮现在脑海:部门一共十个人出去旅游,必须10个人上车之后大巴才能开车,下面就来模拟这个上车的过程。&lt;br&gt;
</summary>
<category term="并发" scheme="http://zhengweishan.oschina.io/categories/%E5%B9%B6%E5%8F%91/"/>
<category term="并发,CountDownLatch" scheme="http://zhengweishan.oschina.io/tags/%E5%B9%B6%E5%8F%91%EF%BC%8CCountDownLatch/"/>
</entry>
<entry>
<title>spring boot + mybatis + quartz + druid + swagger2</title>
<link href="http://zhengweishan.oschina.io/2017/03/24/spring-boot-demo/"/>
<id>http://zhengweishan.oschina.io/2017/03/24/spring-boot-demo/</id>
<published>2017-03-23T16:00:00.000Z</published>
<updated>2017-03-27T10:28:17.417Z</updated>
<content type="html"><![CDATA[<p>spring boot + mybatis + quartz + druid + Swagger2 演示demo</p>
<p>说明:主要演示如何整合,简单的任务调用。</p>
<p>环境准备:</p>
<ul>
<li>jdk:1.7</li>
<li>maven:3.2.3</li>
<li>开发工具:IDEA</li>
</ul>
<p>源码地址:</p>
<p>gitosc: <a href="https://git.oschina.net/zhengweishan/spring-boot_demo" target="_blank" rel="external">https://git.oschina.net/zhengweishan/spring-boot_demo</a></p>
<p>github: <a href="https://github.com/wesley5201314/spring-boot-demo" target="_blank" rel="external">https://github.com/wesley5201314/spring-boot-demo</a></p>
<p>项目结构:</p>
<p><img src="http://i.imgur.com/LNzimT3.png" alt=""></p>
<a id="more"></a>
<p><strong>备注:</strong><br>每个包的作用大家一看就明白了,这里主要说明下application.properties:这里主要配置针对于不同的环境用那个配置文件,这里我只提供了开发,测试的环境属性文件。配置如下:</p>
<pre><code>spring.profiles.active = dev
</code></pre><p>应用启动:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">//启动入口</span></div><div class="line"><span class="meta">@SpringBootApplication</span></div><div class="line"><span class="meta">@ServletComponentScan</span> <span class="comment">//扫描Servlet</span></div><div class="line"><span class="meta">@MapperScan</span>(<span class="string">"com.springboot.demo.dao"</span>) <span class="comment">//扫描dao</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">App</span> </span></div><div class="line">&#123;</div><div class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line"> SpringApplication.run(App.class, args);</div><div class="line"> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>启动之后访问:<br>durid : <a href="http://localhost:8080/druid/index.html" target="_blank" rel="external">http://localhost:8080/druid/index.html</a> 如图:</p>
<p><img src="http://i.imgur.com/qD8hyb4.png" alt=""></p>
<p>登录之后:</p>
<p><img src="http://i.imgur.com/Eb4k89i.png" alt=""></p>
<p>配置代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">//过滤资源</span></div><div class="line"><span class="meta">@WebFilter</span>(filterName=<span class="string">"druidWebStatFilter"</span>,urlPatterns=<span class="string">"/*"</span>,</div><div class="line"> initParams=&#123;</div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"exclusions"</span>,value=<span class="string">"*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"</span>)<span class="comment">// 忽略资源</span></div><div class="line"> &#125;</div><div class="line">)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DruidStatFilter</span> <span class="keyword">extends</span> <span class="title">WebStatFilter</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//配置访问路径,用户名,密码</span></div><div class="line"><span class="meta">@WebServlet</span>(urlPatterns = <span class="string">"/druid/*"</span>, </div><div class="line"> initParams=&#123;</div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"allow"</span>,value=<span class="string">""</span>),<span class="comment">// IP白名单 (没有配置或者为空,则允许所有访问)</span></div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"deny"</span>,value=<span class="string">""</span>),<span class="comment">// IP黑名单 (存在共同时,deny优先于allow)</span></div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"loginUsername"</span>,value=<span class="string">"root"</span>),<span class="comment">// 用户名</span></div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"loginPassword"</span>,value=<span class="string">"root"</span>),<span class="comment">// 密码</span></div><div class="line"> <span class="meta">@WebInitParam</span>(name=<span class="string">"resetEnable"</span>,value=<span class="string">"false"</span>)<span class="comment">// 禁用HTML页面上的“Reset All”功能</span></div><div class="line"> &#125;)</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DruidStatViewServlet</span> <span class="keyword">extends</span> <span class="title">StatViewServlet</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</div><div class="line"> <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>swagger2 : <a href="http://localhost:8080/swagger-ui.html" target="_blank" rel="external">http://localhost:8080/swagger-ui.html</a> 如图:</p>
<p><img src="http://i.imgur.com/MkwOuR0.png" alt=""></p>
<p><img src="http://i.imgur.com/8U2WVwG.png" alt=""></p>
<p>配置代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">//SwaggerConfig</span></div><div class="line"><span class="meta">@Configuration</span></div><div class="line"><span class="meta">@EnableSwagger</span>2</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SwaggerConfig</span> </span>&#123;</div><div class="line"> <span class="comment">/**</span></div><div class="line"> * 可以定义多个组,比如本类中定义把test和demo区分开了 (访问页面就可以看到效果了)</div><div class="line"> * </div><div class="line"> */</div><div class="line"> <span class="meta">@Bean</span></div><div class="line"> <span class="function"><span class="keyword">public</span> Docket <span class="title">testApi</span><span class="params">()</span> </span>&#123;</div><div class="line"> <span class="keyword">return</span> <span class="keyword">new</span> Docket(DocumentationType.SWAGGER_2)</div><div class="line"> .apiInfo(apiInfo())</div><div class="line"> .select()</div><div class="line"> .apis(RequestHandlerSelectors</div><div class="line"> .basePackage(<span class="string">"com.springboot.demo.controller"</span>))</div><div class="line"> .paths(PathSelectors.any()).build();</div><div class="line"> &#125;</div><div class="line"> </div><div class="line"></div><div class="line"> <span class="function"><span class="keyword">private</span> ApiInfo <span class="title">apiInfo</span><span class="params">()</span> </span>&#123;</div><div class="line"> ApiInfo apiInfo = <span class="keyword">new</span> ApiInfo(<span class="string">"SpringBootDemo"</span>, <span class="comment">// 大标题</span></div><div class="line"> <span class="string">"Spring boot + swagger + mybatis + druid"</span>, <span class="comment">// 小标题</span></div><div class="line"> <span class="string">"1.0"</span>, <span class="comment">// 版本</span></div><div class="line"> <span class="string">"spring-boot-demo"</span>,</div><div class="line"> <span class="string">"zhengweishan"</span>, <span class="comment">// 作者</span></div><div class="line"> <span class="string">"blog"</span>, <span class="comment">// 链接显示文字</span></div><div class="line"> <span class="string">"http://zhengweishan.oschina.io/"</span><span class="comment">// 网站链接</span></div><div class="line"> );</div><div class="line"> <span class="keyword">return</span> apiInfo;</div><div class="line"> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>添加jsp支持</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="keyword">import</span> com.springboot.demo.App;</div><div class="line"><span class="keyword">import</span> org.springframework.boot.builder.SpringApplicationBuilder;</div><div class="line"><span class="keyword">import</span> org.springframework.boot.context.web.SpringBootServletInitializer;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * Created by wesley on 2017-03-24.</div><div class="line"> * spring boot jsp支持</div><div class="line"> */</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JspInitContext</span> <span class="keyword">extends</span> <span class="title">SpringBootServletInitializer</span> </span>&#123;</div><div class="line"></div><div class="line"> <span class="meta">@Override</span></div><div class="line"> <span class="function"><span class="keyword">protected</span> SpringApplicationBuilder <span class="title">configure</span><span class="params">(SpringApplicationBuilder application)</span> </span>&#123;</div><div class="line"> <span class="keyword">return</span> application.sources(App.class);</div><div class="line"> &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>配置文件配置添加如下:</p>
<pre><code>#jsp视图设置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
</code></pre>]]></content>
<summary type="html">
&lt;p&gt;spring boot + mybatis + quartz + druid + Swagger2 演示demo&lt;/p&gt;
&lt;p&gt;说明:主要演示如何整合,简单的任务调用。&lt;/p&gt;
&lt;p&gt;环境准备:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;jdk:1.7&lt;/li&gt;
&lt;li&gt;maven:3.2.3&lt;/li&gt;
&lt;li&gt;开发工具:IDEA&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;源码地址:&lt;/p&gt;
&lt;p&gt;gitosc: &lt;a href=&quot;https://git.oschina.net/zhengweishan/spring-boot_demo&quot;&gt;https://git.oschina.net/zhengweishan/spring-boot_demo&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;github: &lt;a href=&quot;https://github.com/wesley5201314/spring-boot-demo&quot;&gt;https://github.com/wesley5201314/spring-boot-demo&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;项目结构:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/LNzimT3.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</summary>
<category term="SpringBoot" scheme="http://zhengweishan.oschina.io/categories/SpringBoot/"/>
<category term="SpingBoot" scheme="http://zhengweishan.oschina.io/tags/SpingBoot/"/>
</entry>
<entry>
<title>分布式rpc框架</title>
<link href="http://zhengweishan.oschina.io/2017/03/23/boy-rpc-framework/"/>
<id>http://zhengweishan.oschina.io/2017/03/23/boy-rpc-framework/</id>
<published>2017-03-22T16:00:00.000Z</published>
<updated>2017-03-23T02:53:29.037Z</updated>
<content type="html"><![CDATA[<h2 id="什么是RPC"><a href="#什么是RPC" class="headerlink" title="什么是RPC"></a>什么是RPC</h2><p>RPC(Remote Procedure Call Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。说得通俗一点就是:调用远程计算机上的服务,就像调用本地服务一样。它可以有不同的实现方式:如RMI(远程方法调用)、Hessian、Http invoker等。另外,RPC是与语言无关的。</p>
<p>RPC示意图(来源网络)<br><img src="http://i.imgur.com/NxofKwx.png" alt=""></p>
<a id="more"></a>
<h2 id="如何开发一个rpc框架"><a href="#如何开发一个rpc框架" class="headerlink" title="如何开发一个rpc框架"></a>如何开发一个rpc框架</h2><p>首先我们要考虑我们这个rpc框架需要具备哪些东西,比如:用什么作为底层协议,是否支持高并发,是否支持高效的序列化方式,能否同时具备服务的发现与注册。</p>
<p>RPC 可基于 HTTP 或 TCP 协议,Web Service 就是基于 HTTP 协议的 RPC,它具有良好的跨平台性,但其性能却不如基于 TCP 协议的 RPC。会两方面会直接影响 RPC 的性能,一是传输方式,二是序列化。</p>
<p>众所周知,TCP 是传输层协议,HTTP 是应用层协议,而传输层较应用层更加底层,在数据传输方面,越底层越快,因此,在一般情况下,TCP 一定比 HTTP 快。就序列化而言,Java 提供了默认的序列化方式,但在高并发的情况下,这种方式将会带来一些性能上的瓶颈,于是市面上出现了一系列优秀的序列化框架,比如:Protobuf、Kryo、Hessian、Jackson 等,它们可以取代 Java 默认的序列化,从而提供更高效的性能。</p>
<p>为了支持高并发,传统的阻塞式 IO 显然不太合适,因此我们需要异步的 IO,即 NIO。Java 提供了 NIO 的解决方案,Java 7 也提供了更优秀的 NIO.2 支持,用 Java 实现 NIO 并不是遥不可及的事情,只是需要我们熟悉 NIO 的技术细节。</p>
<p>我们需要将服务部署在分布式环境下的不同节点上,通过服务注册的方式,让客户端来自动发现当前可用的服务,并调用这些服务。这需要一种服务注册表(Service Registry)的组件,让它来注册分布式环境下所有的服务地址(包括:主机名与端口号)。</p>
<p>应用、服务、服务注册表之间的关系见下图:</p>
<p><img src="http://i.imgur.com/QeMu3tX.png" alt=""></p>
<p>每台 Server 上可发布多个 Service,这些 Service 共用一个 host 与 port,在分布式环境下会提供 Server 共同对外提供 Service。此外,为防止 Service Registry 出现单点故障,因此需要将其搭建为集群环境。</p>
<p>综合考虑,我们可以选用以下技术作为我们开发rpc框架的技术选型:</p>
<ol>
<li>Spring:它是最强大的依赖注入框架,也是业界的权威标准。</li>
<li>Netty:它使 NIO 编程更加容易,屏蔽了 Java 底层的 NIO 细节。</li>
<li>Protostuff:它基于 Protobuf 序列化框架,面向 POJO,无需编写 .proto 文件。</li>
<li>ZooKeeper/redis:提供服务注册与发现功能,开发分布式系统的必备选择,同时它也具备天生的集群能力。</li>
</ol>
<h2 id="开发准备"><a href="#开发准备" class="headerlink" title="开发准备"></a>开发准备</h2><p>项目整体构思如图:</p>
<p><img src="http://i.imgur.com/2Oj5TyE.png" alt=""></p>
<p>各部分的作用:</p>
<p><img src="http://i.imgur.com/DkGd4Cy.png" alt=""></p>
<h2 id="开发流程"><a href="#开发流程" class="headerlink" title="开发流程"></a>开发流程</h2><p>开发之前我们先看下整个服务的请求流程:<br><img src="http://i.imgur.com/g1txCNQ.png" alt=""></p>
<p>这里用redis作为注册中心,来演示一个开发过程。</p>
<h3 id="编写服务接口:"><a href="#编写服务接口:" class="headerlink" title="编写服务接口:"></a>编写服务接口:</h3><pre><code>public interface HelloRedisService {
String sayHello(String str);
}
</code></pre><p>将该接口放在独立的客户端 jar 包中,以供应用使用。</p>
<h3 id="编写服务接口实现类:"><a href="#编写服务接口实现类:" class="headerlink" title="编写服务接口实现类:"></a>编写服务接口实现类:</h3><pre><code>@BoyRpcService(HelloRedisService.class)
public class HelloRedisServiceImpl implements HelloRedisService {
@Override
public String sayHello(String str) {
return &quot;redis say:&quot;+str+&quot;,Hello!&quot;;
}
}
</code></pre><p>BoyRpcService注解定义在服务接口的实现类上,需要对该实现类指定远程接口,因为实现类可能会实现多个接口,一定要告诉框架哪个才是远程接口。</p>
<pre><code>@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface BoyRpcService {
/**
* 服务接口类
*/
Class&lt;?&gt; value();
/**
* 服务版本号
*/
String version() default &quot;&quot;;
}
</code></pre><p>该注解具备 Spring 的Component注解的特性,可被 Spring 扫描。</p>
<p>该实现类放在服务端 jar 包中,该 jar 包还提供了一些服务端的配置文件与启动服务的引导程序。</p>
<h3 id="配置服务端:"><a href="#配置服务端:" class="headerlink" title="配置服务端:"></a>配置服务端:</h3><p>服务端 Spring 配置文件名为spring-by-redis.xml,内容如下:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
&lt;context:component-scan base-package=&quot;com.boy.rpc.framework.sample.server&quot;/&gt;
&lt;context:property-placeholder location=&quot;classpath:rpc-redis.properties&quot;/&gt;
&lt;bean id=&quot;redisConfig&quot; class=&quot;com.boy.rpc.framework.registry.redis.bean.RedisConfig&quot;&gt;
&lt;property name=&quot;redisAddress&quot; value=&quot;${rpc.registry_address}&quot;/&gt;
&lt;property name=&quot;redisPassword&quot; value=&quot;${rpc.registry_password}&quot;/&gt;
&lt;property name=&quot;redisPort&quot; value=&quot;${rpc.registry_port}&quot;/&gt;
&lt;/bean&gt;
&lt;bean id=&quot;serviceRegistry&quot; class=&quot;com.boy.rpc.framework.registry.redis.RedisServiceRegistry&quot;&gt;
&lt;constructor-arg name=&quot;redisConfig&quot; ref =&quot;redisConfig&quot;/&gt;
&lt;/bean&gt;
&lt;bean id=&quot;rpcServer&quot; class=&quot;com.boy.rpc.framework.server.BoyRpcServer&quot;&gt;
&lt;constructor-arg name=&quot;serviceAddress&quot; value=&quot;${rpc.redis_service_address}&quot;/&gt;
&lt;constructor-arg name=&quot;serviceRegistry&quot; ref=&quot;serviceRegistry&quot;/&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre><p>具体的配置参数在rpc-redis.properties文件中,内容如下:</p>
<pre><code>#服务部署地址#
rpc.redis_service_address = 127.0.0.1:8081
#注册中心地址#
rpc.registry_address = 127.0.0.1
#注册中心端口#
rpc.registry_port = 6379
#注册中心密码#
rpc.registry_password = 25362e3e047b413d:Redis123
</code></pre><p>以上配置表明:连接本地的 redis 服务器,并在 8081 端口上发布 RPC 服务。</p>
<h2 id="启动服务器并发布服务:"><a href="#启动服务器并发布服务:" class="headerlink" title="启动服务器并发布服务:"></a>启动服务器并发布服务:</h2><pre><code>public class RedisRpcBootstrap {
private static final Logger logger = LoggerFactory.getLogger(RedisRpcBootstrap.class);
public static void main(String[] args) {
logger.debug(&quot;redis rpc start server&quot;);
new ClassPathXmlApplicationContext(&quot;spring-by-redis.xml&quot;);
}
}
</code></pre><h2 id="实现服务注册"><a href="#实现服务注册" class="headerlink" title="实现服务注册:"></a>实现服务注册:</h2><pre><code>public class RedisServiceRegistry implements ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(RedisServiceRegistry.class);
private RedisClient redisClient = null;
public RedisServiceRegistry(RedisConfig redisConfig){
redisClient = new RedisClient(redisConfig);
}
@Override
public void register(String serviceName, String serviceAddress) {
logger.debug(&quot;redis register start!&quot;);
if(redisClient.existsKey(serviceName)){
List&lt;String&gt; oldList = (List&lt;String&gt;) redisClient.getObject(serviceName);
oldList.add(serviceAddress);
logger.debug(&quot;service exits create service address : {}&quot;, oldList);
redisClient.setObject(serviceName,oldList);
}else{
List&lt;String&gt; addressList = new ArrayList&lt;&gt;();
addressList.add(serviceAddress);
logger.debug(&quot;service not exits create service address : {}&quot;, addressList);
redisClient.setObject(serviceName,addressList);
}
logger.debug(&quot;redis register end!&quot;);
}
}
</code></pre><h2 id="实现-RPC-服务器"><a href="#实现-RPC-服务器" class="headerlink" title="实现 RPC 服务器:"></a>实现 RPC 服务器:</h2><p>使用 Netty 可实现一个支持 NIO 的 RPC 服务器,需要使用ServiceRegistry注册服务地址,代码如下</p>
<pre><code>public class BoyRpcServer implements ApplicationContextAware, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(BoyRpcServer.class);
private String serviceAddress;
private ServiceRegistry serviceRegistry;
/**
* 存放 服务名 与 服务对象 之间的映射关系
*/
private Map&lt;String, Object&gt; handlerMap = new HashMap&lt;&gt;();
public BoyRpcServer(String serviceAddress) {
this.serviceAddress = serviceAddress;
}
public BoyRpcServer(String serviceAddress, ServiceRegistry serviceRegistry) {
this.serviceAddress = serviceAddress;
this.serviceRegistry = serviceRegistry;
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
// 扫描带有 RpcService 注解的类并初始化 handlerMap 对象
Map&lt;String, Object&gt; serviceBeanMap = ctx.getBeansWithAnnotation(BoyRpcService.class);
if (MapUtils.isNotEmpty(serviceBeanMap)) {
for (Object serviceBean : serviceBeanMap.values()) {
BoyRpcService rpcService = serviceBean.getClass().getAnnotation(BoyRpcService.class);
String serviceName = rpcService.value().getName();
String serviceVersion = rpcService.version();
if (StringUtil.isNotEmpty(serviceVersion)) {
serviceName += &quot;-&quot; + serviceVersion;
}
handlerMap.put(serviceName, serviceBean);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// 创建并初始化 Netty 服务端 Bootstrap 对象
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer&lt;SocketChannel&gt;() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new BoyRpcDecoder(BoyRpcRequest.class)); // 解码 RPC 请求
pipeline.addLast(new BoyRpcEncoder(BoyRpcResponse.class)); // 编码 RPC 响应
pipeline.addLast(new BoyRpcServerHandler(handlerMap)); // 处理 RPC 请求
}
});
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
// 获取 RPC 服务器的 IP 地址与端口号
String[] addressArray = StringUtil.split(serviceAddress, &quot;:&quot;);
String ip = addressArray[0];
int port = Integer.parseInt(addressArray[1]);
// 启动 RPC 服务器
ChannelFuture future = bootstrap.bind(ip, port).sync();
// 注册 RPC 服务地址
if (serviceRegistry != null) {
for (String interfaceName : handlerMap.keySet()) {
serviceRegistry.register(interfaceName, serviceAddress);
logger.debug(&quot;register service: {} =&gt; {}&quot;, interfaceName, serviceAddress);
}
}
logger.debug(&quot;server started on port {}&quot;, port);
// 关闭 RPC 服务器
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
</code></pre><p>以上代码中,有两个重要的 POJO 需要描述一下,它们分别是BoyRpcRequest与BoyRpcResponse。使用RpcRequest封装 RPC 请求,使用RpcResponse封装 RPC 响应.使用BoyRpcDecoder提供 RPC 解码,只需扩展 Netty 的ByteToMessageDecoder抽象类的decode方法即可,使用BoyRpcEncoder提供 RPC 编码,只需扩展 Netty 的MessageToByteEncoder抽象类的encode方法即可.使用RpcHandler中处理 RPC 请求,只需扩展 Netty 的SimpleChannelInboundHandler抽象类即可,具体代码才看源码:</p>
<p><a href="https://git.oschina.net/zhengweishan/boy-rpc-framework" target="_blank" rel="external">https://git.oschina.net/zhengweishan/boy-rpc-framework</a></p>
<h2 id="配置客户端:"><a href="#配置客户端:" class="headerlink" title="配置客户端:"></a>配置客户端:</h2><p>同样使用 Spring 配置文件来配置 RPC 客户端,spring-by-redis.xml代码如下:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
&lt;context:property-placeholder location=&quot;classpath:rpc-redis.properties&quot;/&gt;
&lt;bean id=&quot;redisConfig&quot; class=&quot;com.boy.rpc.framework.registry.redis.bean.RedisConfig&quot;&gt;
&lt;property name=&quot;redisAddress&quot; value=&quot;${rpc.registry_address}&quot;/&gt;
&lt;property name=&quot;redisPassword&quot; value=&quot;${rpc.registry_password}&quot;/&gt;
&lt;property name=&quot;redisPort&quot; value=&quot;${rpc.registry_port}&quot;/&gt;
&lt;/bean&gt;
&lt;bean id=&quot;serviceDiscovery&quot; class=&quot;com.boy.rpc.framework.registry.redis.RedisServiceDiscovery&quot;&gt;
&lt;constructor-arg name=&quot;redisConfig&quot; ref=&quot;redisConfig&quot;/&gt;
&lt;/bean&gt;
&lt;bean id=&quot;rpcProxy&quot; class=&quot;com.boy.rpc.framework.client.BoyRpcProxy&quot;&gt;
&lt;constructor-arg name=&quot;serviceDiscovery&quot; ref=&quot;serviceDiscovery&quot;/&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre><p>其中rpc-redis.properties提供了具体的配置:</p>
<pre><code>#redis注册中心地址#
rpc.registry_address = 127.0.0.1
#redis注册中心端口#
rpc.registry_port = 6379
#redis注册中心密码#
rpc.registry_password = 25362e3e047b413d:Redis123
</code></pre><h2 id="实现服务发现"><a href="#实现服务发现" class="headerlink" title="实现服务发现:"></a>实现服务发现:</h2><p>同样使用 redis 实现服务发现功能,见如下代码:</p>
<pre><code>public class RedisServiceDiscovery implements ServiceDiscovery {
private static final Logger logger = LoggerFactory.getLogger(RedisServiceRegistry.class);
private RedisClient redisClient = null;
public RedisServiceDiscovery(RedisConfig redisConfig) {
redisClient = new RedisClient(redisConfig);
}
@Override
public String discover(String serviceName) {
String address = null;
if(redisClient.existsKey(serviceName)){
List&lt;String&gt; list = (List&lt;String&gt;) redisClient.getObject(serviceName);
int size = list.size();
if(size == 1){
//只有一个地址
address = list.get(0);
logger.debug(&quot;get only address : {}&quot;, address);
} else {
// 若存在多个地址,则随机获取一个地址
address = list.get(ThreadLocalRandom.current().nextInt(size));
logger.debug(&quot;get random address : {}&quot;, address);
}
}
return address;
}
}
</code></pre><h2 id="实现-RPC-代理"><a href="#实现-RPC-代理" class="headerlink" title="实现 RPC 代理:"></a>实现 RPC 代理:</h2><p>这里使用 Java 提供的动态代理技术实现 RPC 代理(当然也可以使用 CGLib 来实现),具体代码如下:</p>
<pre><code>public class BoyRpcProxy {
private static final Logger logger = LoggerFactory.getLogger(BoyRpcProxy.class);
private String serviceAddress;
private ServiceDiscovery serviceDiscovery;
public BoyRpcProxy(String serviceAddress) {
this.serviceAddress = serviceAddress;
}
public BoyRpcProxy(ServiceDiscovery serviceDiscovery) {
this.serviceDiscovery = serviceDiscovery;
}
@SuppressWarnings(&quot;unchecked&quot;)
public &lt;T&gt; T create(final Class&lt;?&gt; interfaceClass) {
return create(interfaceClass, &quot;&quot;);
}
@SuppressWarnings(&quot;unchecked&quot;)
public &lt;T&gt; T create(final Class&lt;?&gt; interfaceClass, final String serviceVersion) {
// 创建动态代理对象
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class&lt;?&gt;[]{interfaceClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 创建 RPC 请求对象并设置请求属性
BoyRpcRequest request = new BoyRpcRequest();
request.setRequestId(UUID.randomUUID().toString());
request.setInterfaceName(method.getDeclaringClass().getName());
request.setServiceVersion(serviceVersion);
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
// 获取 RPC 服务地址
if (serviceDiscovery != null) {
String serviceName = interfaceClass.getName();
if (StringUtil.isNotEmpty(serviceVersion)) {
serviceName += &quot;-&quot; + serviceVersion;
}
serviceAddress = serviceDiscovery.discover(serviceName);
logger.debug(&quot;discover service: {} =&gt; {}&quot;, serviceName, serviceAddress);
}
if (StringUtil.isEmpty(serviceAddress)) {
throw new RuntimeException(&quot;server address is empty&quot;);
}
// 从 RPC 服务地址中解析主机名与端口号
String[] array = StringUtil.split(serviceAddress, &quot;:&quot;);
String host = array[0];
int port = Integer.parseInt(array[1]);
// 创建 RPC 客户端对象并发送 RPC 请求
BoyRpcClient client = new BoyRpcClient(host, port);
long time = System.currentTimeMillis();
BoyRpcResponse response = client.send(request);
logger.debug(&quot;time: {}ms&quot;, System.currentTimeMillis() - time);
if (response == null) {
throw new RuntimeException(&quot;response is null&quot;);
}
// 返回 RPC 响应结果
if (response.hasException()) {
throw response.getException();
} else {
return response.getResult();
}
}
}
);
}
}
</code></pre><h2 id="发送-RPC-请求"><a href="#发送-RPC-请求" class="headerlink" title="发送 RPC 请求:"></a>发送 RPC 请求:</h2><p>使用 main 方法结合 Spring 编写一个测试,代码如下:</p>
<pre><code>public class RedisHelloClient {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext(&quot;spring-by-redis.xml&quot;);
BoyRpcProxy rpcProxy = context.getBean(BoyRpcProxy.class);
HelloRedisService helloService = rpcProxy.create(HelloRedisService.class);
String result = helloService.sayHello(&quot;World&quot;);
System.out.println(result);
System.exit(0);
}
}
</code></pre><p>如果不出意外的话,您应该会看到:redis say:World Hello!</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文通过 Spring + Netty + Protostuff + ZooKeeper/Redis 实现了一个轻量级 RPC 框架,使用 Spring 提供依赖注入与参数配置,使用 Netty 实现 NIO 方式的数据传输,使用 Protostuff 实现对象序列化,使用 ZooKeeper/Redis 实现服务注册与发现。使用该框架,可将服务部署到分布式环境中的任意节点上,客户端通过远程接口来调用服务端的具体实现,让服务端与客户端的开发完全分离,为实现大规模分布式应用提供了基础支持。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;什么是RPC&quot;&gt;&lt;a href=&quot;#什么是RPC&quot; class=&quot;headerlink&quot; title=&quot;什么是RPC&quot;&gt;&lt;/a&gt;什么是RPC&lt;/h2&gt;&lt;p&gt;RPC(Remote Procedure Call Protocol)——远程过程调用协议,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。说得通俗一点就是:调用远程计算机上的服务,就像调用本地服务一样。它可以有不同的实现方式:如RMI(远程方法调用)、Hessian、Http invoker等。另外,RPC是与语言无关的。&lt;/p&gt;
&lt;p&gt;RPC示意图(来源网络)&lt;br&gt;&lt;img src=&quot;http://i.imgur.com/NxofKwx.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</summary>
<category term="rpc" scheme="http://zhengweishan.oschina.io/categories/rpc/"/>
<category term="rpc 分布式" scheme="http://zhengweishan.oschina.io/tags/rpc-%E5%88%86%E5%B8%83%E5%BC%8F/"/>
</entry>
<entry>
<title>Tomcat源码学习(六)--Tomcat_7.0.70 生命周期管理</title>
<link href="http://zhengweishan.oschina.io/2017/02/10/%EF%BC%88%E5%85%AD%EF%BC%89Tomcat_7.0.70%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E7%AE%A1%E7%90%86/"/>
<id>http://zhengweishan.oschina.io/2017/02/10/(六)Tomcat_7.0.70生命周期管理/</id>
<published>2017-02-09T16:00:00.000Z</published>
<updated>2017-03-01T08:53:36.617Z</updated>
<content type="html"><![CDATA[<p><strong>想必大家都知道,从server.xml文件解析出来的各个对象都是容器,比如:Server、Service、Connector等。这些容器都具有新建、初始化完成、启动、停止、失败、销毁等状态。Tomcat的实现机制是通过实现org.apache.catalina.Lifecycle接口来管理。</strong></p>
<h2 id="Tomcat–Lifecycle接口"><a href="#Tomcat–Lifecycle接口" class="headerlink" title="Tomcat–Lifecycle接口"></a>Tomcat–Lifecycle接口</h2><p>定义了容器生命周期、容器状态转换及容器状态迁移事件的监听器注册和移除等主要接口。代码清单:</p>
<pre><code> public interface Lifecycle {
public static final String BEFORE_INIT_EVENT = &quot;before_init&quot;;
public static final String AFTER_INIT_EVENT = &quot;after_init&quot;;
public static final String START_EVENT = &quot;start&quot;;
public static final String BEFORE_START_EVENT = &quot;before_start&quot;;
public static final String AFTER_START_EVENT = &quot;after_start&quot;;
public static final String STOP_EVENT = &quot;stop&quot;;
public static final String BEFORE_STOP_EVENT = &quot;before_stop&quot;;
public static final String AFTER_STOP_EVENT = &quot;after_stop&quot;;
public static final String AFTER_DESTROY_EVENT = &quot;after_destroy&quot;;
public static final String BEFORE_DESTROY_EVENT = &quot;before_destroy&quot;;
public static final String PERIODIC_EVENT = &quot;periodic&quot;;
public static final String CONFIGURE_START_EVENT = &quot;configure_start&quot;;
public static final String CONFIGURE_STOP_EVENT = &quot;configure_stop&quot;;
public void addLifecycleListener(LifecycleListener listener);
public LifecycleListener[] findLifecycleListeners();
public void removeLifecycleListener(LifecycleListener listener);
public void init() throws LifecycleException;
public void start() throws LifecycleException;
public void stop() throws LifecycleException;
public void destroy() throws LifecycleException;
public LifecycleState getState();
public String getStateName();
public interface SingleUse {
}
}
</code></pre><p>其中,最重要的方法时start和stop方法。父组件通过这两个方法来启动/关闭该组件。addLifecycleListener,findLifecycleListeners,removeLifecycleListener三个方法用于向组件注册/查找/删除监听器。当事件发生时,会触发监听器。接口中还定义了相关事件。</p>
<a id="more"></a>
<p>下面从一幅图来了解Tomcat涉及生命周期管理的主要类:</p>
<p><img src="http://i.imgur.com/ZIi07NG.jpg" alt=""></p>
<ul>
<li>Lifecycle:定义了容器生命周期、容器状态转换及容器状态迁移事件的监听器注册和移除等主要接口;</li>
<li>LifecycleBase:作为Lifecycle接口的抽象实现类,运用抽象模板模式将所有容器的生命周期及状态转换衔接起来,此外还提供了生成LifecycleEvent事件的接口;</li>
<li>LifecycleSupport:提供有关LifecycleEvent事件的监听器注册、移除,并且使用经典的监听器模式,实现事件生成后触打监听器的实现;</li>
<li>MBeanRegistration:Java jmx框架提供的注册MBean的接口,引入此接口是为了便于使用JMX提供的管理功能;</li>
<li>LifecycleMBeanBase:Tomcat提供的对MBeanRegistration的抽象实现类,运用抽象模板模式将所有容器统一注册到JMX;</li>
</ul>
<p>从上图可以看出ContainerBase、StandardServer、StandardService、WebappLoader、Connector、StandardContext、StandardEngine、StandardHost、StandardWrapper等容器都继承了LifecycleMBeanBase,因此这些容器都具有了同样的生命周期并可以通过JMX进行管理。</p>
<h2 id="什么是JMX"><a href="#什么是JMX" class="headerlink" title="什么是JMX?"></a>什么是JMX?</h2><p>JMX(Java Management Extensions,即Java管理扩展)是一个为应用程序、设备、系统等植入管理功能的框架。JMX可以跨越一系列异构操作系统平台、系统体系结构和网络传输协议,灵活的开发无缝集成的系统、网络和服务管理应用。</p>
<p><img src="http://i.imgur.com/nHRPZr2.jpg" alt=""></p>
<p>JMX体系结构分为以下四个层次:</p>
<p><strong>设备层</strong></p>
<p>设备层(Instrumentation Level):主要定义了信息模型。在JMX中,各种管理对象以管理构件的形式存在,需要管理时,向MBean服务器进行注册。该层还定义了通知机制以及一些辅助元数据类。</p>
<p><strong>代理层</strong></p>
<p>代理层(Agent Level):主要定义了各种服务以及通信模型。该层的核心是一个MBean服务器,所有的管理构件都需要向它注册,才能被管理。注册在MBean服务器上管理构件并不直接和远程应用程序进行通信,它们通过协议适配器和连接器进行通信。而协议适配器和连接器也以管理构件的形式向MBean服务器注册才能提供相应的服务。</p>
<p><strong>分布服务层</strong></p>
<p>分布服务层(Distributed Service Level):主要定义了能对代理层进行操作的管理接口和构件,这样管理者就可以操作代理。然而,当前的JMX规范并没有给出这一层的具体规范。</p>
<p><strong>附加管理协议API</strong></p>
<p>定义的API主要用来支持当前已经存在的网络管理协议,如SNMP、TMN、CIM/WBEM等。</p>
<h2 id="Tomcat–事件、监听"><a href="#Tomcat–事件、监听" class="headerlink" title="Tomcat–事件、监听"></a>Tomcat–事件、监听</h2><p>每个容器由于继承自LifecycleBase,当容器状态发生变化时,都会调用fireLifecycleEvent方法,生成LifecycleEvent,并且交由此容器的事件监听器处理。</p>
<p>LifecycleBase的fireLifecycleEvent方法的实现:</p>
<pre><code> protected void fireLifecycleEvent(String type, Object data) {
lifecycle.fireLifecycleEvent(type, data);
}
//lifecycle定义
private LifecycleSupport lifecycle = new LifecycleSupport(this);
//LifecycleSupport的fireLifecycleEvent方法的实现
public void fireLifecycleEvent(String type, Object data) {
LifecycleEvent event = new LifecycleEvent(lifecycle, type, data);
LifecycleListener interested[] = listeners;
for (int i = 0; i &lt; interested.length; i++)
interested[i].lifecycleEvent(event);
}
</code></pre><p>然后将事件通知给所有监听当前容器的生命周期监听器LifecycleListener,并调用LifecycleListener的lifecycleEvent方法。</p>
<p>那么监听器LifecycleListener是何时注册进来的?其实每个容器在新建、初始化、启动,销毁,被添加到父容器的过程中都会调用父类LifecycleBase的addLifecycleListener方法:</p>
<pre><code> public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
</code></pre><p>LifecycleBase的addLifecycleListener方法实际是对LifecycleSupport的addLifecycleListener方法的简单代理,LifecycleSupport的addLifecycleListener方法的实现:</p>
<pre><code>public void addLifecycleListener(LifecycleListener listener) {
synchronized (listenersLock) {
LifecycleListener results[] =
new LifecycleListener[listeners.length + 1];
for (int i = 0; i &lt; listeners.length; i++)
results[i] = listeners[i];
results[listeners.length] = listener;
listeners = results;
}
}
</code></pre><p>容器会最终调用每个对此容器感兴趣的LifecycleListener的lifecycleEvent方法,那么LifecycleListener的lifecycleEvent方法会做些什么呢?为了简单起见,我们以监听器JasperListener为例,JasperListener的lifecycleEvent方法的实现:</p>
<pre><code> public void lifecycleEvent(LifecycleEvent event) {
if (Lifecycle.BEFORE_INIT_EVENT.equals(event.getType())) {
try {
// Set JSP factory
Class.forName(&quot;org.apache.jasper.compiler.JspRuntimeContext&quot;,
true,
this.getClass().getClassLoader());
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// Should not occur, obviously
log.warn(&quot;Couldn&apos;t initialize Jasper&quot;, t);
}
// Another possibility is to do directly:
// JspFactory.setDefaultFactory(new JspFactoryImpl());
}
}
</code></pre><h2 id="Tomcat–容器生命周期"><a href="#Tomcat–容器生命周期" class="headerlink" title="Tomcat–容器生命周期"></a>Tomcat–容器生命周期</h2><p>StandardServer、StandardService、Connector、StandardContext这些容器,彼此之间都有父子关系,每个容器都可能包含零个或者多个子容器,这些子容器可能存在不同类型或者相同类型的多个。在一个容器创建成功后,会有以下状态:</p>
<ul>
<li><p>NEW:容器刚刚创建时,即在LifecycleBase实例构造完成时的状态。</p>
</li>
<li><p>INITIALIZED:容器初始化完成时的状态。</p>
</li>
<li><p>STARTING_PREP:容器启动前的状态。</p>
</li>
<li><p>STARTING:容器启动过程中的状态。</p>
</li>
<li><p>STARTED:容器启动完成的状态。</p>
</li>
<li><p>STOPPING_PREP:容器停止前的状态。</p>
</li>
<li><p>STOPPING:容器停止过程中的状态。</p>
</li>
<li><p>STOPPED:容器停止完成的状态。</p>
</li>
<li><p>DESTROYED:容器销毁后的状态。</p>
</li>
<li><p>FAILED:容器启动、停止过程中出现异常的状态。</p>
</li>
<li><p>MUST_STOP:此状态未使用。</p>
</li>
<li><p>MUST_DESTROY:此状态未使用。</p>
</li>
</ul>
<p>这些状态都定义在枚举类LifecycleState中。代码详单:</p>
<pre><code>public enum LifecycleState {
NEW(false, null),
INITIALIZING(false, Lifecycle.BEFORE_INIT_EVENT),
INITIALIZED(false, Lifecycle.AFTER_INIT_EVENT),
STARTING_PREP(false, Lifecycle.BEFORE_START_EVENT),
STARTING(true, Lifecycle.START_EVENT),
STARTED(true, Lifecycle.AFTER_START_EVENT),
STOPPING_PREP(true, Lifecycle.BEFORE_STOP_EVENT),
STOPPING(false, Lifecycle.STOP_EVENT),
STOPPED(false, Lifecycle.AFTER_STOP_EVENT),
DESTROYING(false, Lifecycle.BEFORE_DESTROY_EVENT),
DESTROYED(false, Lifecycle.AFTER_DESTROY_EVENT),
FAILED(false, null),
/**
* @deprecated Unused. Will be removed in Tomcat 9.0.x. The state transition
* checking in {@link org.apache.catalina.util.LifecycleBase}
* makes it impossible to use this state. The intended behaviour
* can be obtained by setting the state to
* {@link LifecycleState#FAILED} in
* &lt;code&gt;LifecycleBase.startInternal()&lt;/code&gt;
*/
@Deprecated
MUST_STOP(true, null),
/**
* @deprecated Unused. Will be removed in Tomcat 9.0.x. The state transition
* checking in {@link org.apache.catalina.util.LifecycleBase}
* makes it impossible to use this state. The intended behaviour
* can be obtained by implementing {@link Lifecycle.SingleUse}.
*/
@Deprecated
MUST_DESTROY(false, null);
private final boolean available;
private final String lifecycleEvent;
private LifecycleState(boolean available, String lifecycleEvent) {
this.available = available;
this.lifecycleEvent = lifecycleEvent;
}
/**
* May the public methods other than property getters/setters and lifecycle
* methods be called for a component in this state? It returns
* &lt;code&gt;true&lt;/code&gt; for any component in any of the following states:
* &lt;ul&gt;
* &lt;li&gt;{@link #STARTING}&lt;/li&gt;
* &lt;li&gt;{@link #STARTED}&lt;/li&gt;
* &lt;li&gt;{@link #STOPPING_PREP}&lt;/li&gt;
* &lt;li&gt;{@link #MUST_STOP}&lt;/li&gt;
* &lt;/ul&gt;
*/
public boolean isAvailable() {
return available;
}
/**
*
*/
public String getLifecycleEvent() {
return lifecycleEvent;
}
}
</code></pre><p>每个容器都会有自身的生命周期,其中也涉及状态的迁移,以及伴随的事件生成。所有容器的状态转换(如新建、初始化、启动、停止等)都是由外到内,由上到下进行,即先执行父容器的状态转换及相关操作,然后再执行子容器的转态转换,这个过程是层层迭代执行的。</p>
<h3 id="Tomcat容器生命周期—-新建"><a href="#Tomcat容器生命周期—-新建" class="headerlink" title="Tomcat容器生命周期—-新建"></a>Tomcat容器生命周期—-新建</h3><p>所有容器在构造的过程中,都会首先对父类LifecycleBase进行构造。LifecycleBase中定义了所有容器的起始状态为LifecycleState.NEW。</p>
<pre><code>private volatile LifecycleState state = LifecycleState.NEW;
</code></pre><h3 id="Tomcat容器生命周期—-初始化"><a href="#Tomcat容器生命周期—-初始化" class="headerlink" title="Tomcat容器生命周期—-初始化"></a>Tomcat容器生命周期—-初始化</h3><p>每个容器的init方法是自身初始化的入口,其初始化过程如图所示:</p>
<p><img src="http://i.imgur.com/qSZYYc3.jpg" alt=""></p>
<ol>
<li>调用方调用容器父类LifecycleBase的init方法,LifecycleBase的init方法主要完成一些所有容器公共抽象出来的动作;</li>
<li>LifecycleBase的init方法调用具体容器的initInternal方法实现,此initInternal方法用于对容器本身真正的初始化;</li>
<li>具体容器的initInternal方法调用父类LifecycleMBeanBase的initInternal方法实现,此initInternal方法用于将容器托管到JMX,便于运维管理;</li>
<li>LifecycleMBeanBase的initInternal方法调用自身的register方法,将容器作为MBean注册到MBeanServer;</li>
<li>容器如果有子容器,会调用子容器的init方法;</li>
<li>容器初始化完毕,LifecycleBase会将容器的状态更改为初始化完毕,即LifecycleState.INITIALIZED。</li>
</ol>
<pre><code>**init方法的实现**
public final synchronized void init() throws LifecycleException {
if (!state.equals(LifecycleState.NEW)) {
invalidTransition(Lifecycle.BEFORE_INIT_EVENT);
}
setStateInternal(LifecycleState.INITIALIZING, null, false);
try {
initInternal();//调用具体容器的initInternal方法实现
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
setStateInternal(LifecycleState.FAILED, null, false);
throw new LifecycleException(
sm.getString(&quot;lifecycleBase.initFail&quot;,toString()), t);
}
setStateInternal(LifecycleState.INITIALIZED, null, false);
}
</code></pre><p>只有当前容器的状态处于LifecycleState.NEW的才可以被初始化,真正执行初始化的方法是initInternal,当初始化完毕,当前容器的状态会被更改为LifecycleState.INITIALIZED。以StandardService这个容器为例举例分析,StandardService容器的initInternal方法实现:</p>
<pre><code> protected void initInternal() throws LifecycleException {
super.initInternal();
if (container != null) {
container.init();
}
// Initialize any Executors
for (Executor executor : findExecutors()) {
if (executor instanceof LifecycleMBeanBase) {
((LifecycleMBeanBase) executor).setDomain(getDomain());
}
executor.init();
}
// Initialize our defined Connectors
synchronized (connectorsLock) {
for (Connector connector : connectors) {
try {
connector.init();
} catch (Exception e) {
String message = sm.getString(
&quot;standardService.connector.initFailed&quot;, connector);
log.error(message, e);
if (Boolean.getBoolean(&quot;org.apache.catalina.startup.EXIT_ON_INIT_FAILURE&quot;))
throw new LifecycleException(message);
}
}
}
}
</code></pre><p>其处理过程:</p>
<p><strong><em>a、调用父类LifecycleBase的initInternal方法,为当前容器创建DynamicMBean,并注册到JMX中。</em></strong></p>
<pre><code>protected void initInternal() throws LifecycleException {
// If oname is not null then registration has already happened via
// preRegister().
if (oname == null) {
mserver = Registry.getRegistry(null, null).getMBeanServer();
oname = register(this, getObjectNameKeyProperties());
}
}
//getObjectNameKeyProperties()方法
public final String getObjectNameKeyProperties() {
return &quot;type=Service&quot;;
}
</code></pre><p>LifecycleBase的register方法会为当前容器创建对应的注册名称,以StandardService为例,getDomain默认返回Catalina,因此StandardService的JMX注册名称默认为Catalina:type=Service,真正的注册在registerComponent方法中实现。</p>
<pre><code>//register方法
protected final ObjectName register(Object obj,
String objectNameKeyProperties) {
// Construct an object name with the right domain
StringBuilder name = new StringBuilder(getDomain());
name.append(&apos;:&apos;);
name.append(objectNameKeyProperties);
ObjectName on = null;
try {
on = new ObjectName(name.toString());
Registry.getRegistry(null, null).registerComponent(obj, on, null);
} catch (MalformedObjectNameException e) {
log.warn(sm.getString(&quot;lifecycleMBeanBase.registerFail&quot;, obj, name),
e);
} catch (Exception e) {
log.warn(sm.getString(&quot;lifecycleMBeanBase.registerFail&quot;, obj, name),
e);
}
return on;
}
//registerComponent方法
public void registerComponent(Object bean, ObjectName oname, String type)
throws Exception
{
if( log.isDebugEnabled() ) {
log.debug( &quot;Managed= &quot;+ oname);
}
if( bean ==null ) {
log.error(&quot;Null component &quot; + oname );
return;
}
try {
if( type==null ) {
type=bean.getClass().getName();
}
ManagedBean managed = findManagedBean(bean.getClass(), type);
// The real mbean is created and registered
DynamicMBean mbean = managed.createMBean(bean);
if( getMBeanServer().isRegistered( oname )) {
if( log.isDebugEnabled()) {
log.debug(&quot;Unregistering existing component &quot; + oname );
}
getMBeanServer().unregisterMBean( oname );
}
getMBeanServer().registerMBean( mbean, oname);
} catch( Exception ex) {
log.error(&quot;Error registering &quot; + oname, ex );
throw ex;
}
}
</code></pre><p>Registry的registerComponent方法会为当前容器(如StandardService)创建DynamicMBean,并且注册到MBeanServer中。</p>
<p><strong><em>b、将StringCache、MBeanFactory、globalNamingResources注册到JMX</em></strong></p>
<p>其中StringCache的注册名为Catalina:type=StringCache,MBeanFactory的注册名为Catalina:type=MBeanFactory,globalNamingResources的注册名为Catalina:type=NamingResources(如StandardService则为:Catalina:type=Service)</p>
<p><strong><em>c、初始化子容器</em></strong></p>
<p>主要对Service子容器进行初始化,默认是StandardService。</p>
<p>注意:个别容器并不完全遵循以上的初始化过程,比如ProtocolHandler作为Connector的子容器,其初始化过程并不是由Connector的initInternal方法调用的,而是与启动过程一道被Connector的startInternal方法所调用。</p>
<h3 id="Tomcat容器生命周期—-容器启动"><a href="#Tomcat容器生命周期—-容器启动" class="headerlink" title="Tomcat容器生命周期—-容器启动"></a>Tomcat容器生命周期—-容器启动</h3><p>每个容器的start方法是自身启动的入口</p>
<p><img src="http://i.imgur.com/tKjahP2.jpg" alt=""></p>
<ol>
<li>调用方调用容器父类LifecycleBase的start方法,LifecycleBase的start方法主要完成一些所有容器公共抽象出来的动作;</li>
<li>LifecycleBase的start方法先将容器状态改为LifecycleState.STARTING_PREP,然后调用具体容器的startInternal方法实现,此startInternal方法用于对容器本身真正的初始化;</li>
<li>具体容器的startInternal方法会将容器状态改为LifecycleState.STARTING,容器如果有子容器,会调用子容器的start方法启动子容器;</li>
<li><p>容器启动完毕,LifecycleBase会将容器的状态更改为启动完毕,即LifecycleState.STARTED。</p>
<pre><code>//LifecycleBase的start方法
public final synchronized void start() throws LifecycleException {
if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
LifecycleState.STARTED.equals(state)) {
if (log.isDebugEnabled()) {
Exception e = new LifecycleException();
log.debug(sm.getString(&quot;lifecycleBase.alreadyStarted&quot;, toString()), e);
} else if (log.isInfoEnabled()) {
log.info(sm.getString(&quot;lifecycleBase.alreadyStarted&quot;, toString()));
}
return;
}
if (state.equals(LifecycleState.NEW)) {
init();
} else if (state.equals(LifecycleState.FAILED)) {
stop();
} else if (!state.equals(LifecycleState.INITIALIZED) &amp;&amp;
!state.equals(LifecycleState.STOPPED)) {
invalidTransition(Lifecycle.BEFORE_START_EVENT);
}
setStateInternal(LifecycleState.STARTING_PREP, null, false);
try {
startInternal();
} catch (Throwable t) {
// This is an &apos;uncontrolled&apos; failure so put the component into the
// FAILED state and throw an exception.
ExceptionUtils.handleThrowable(t);
setStateInternal(LifecycleState.FAILED, null, false);
throw new LifecycleException(sm.getString(&quot;lifecycleBase.startFail&quot;, toString()), t);
}
if (state.equals(LifecycleState.FAILED)) {
// This is a &apos;controlled&apos; failure. The component put itself into the
// FAILED state so call stop() to complete the clean-up.
stop();
} else if (!state.equals(LifecycleState.STARTING)) {
// Shouldn&apos;t be necessary but acts as a check that sub-classes are
// doing what they are supposed to.
invalidTransition(Lifecycle.AFTER_START_EVENT);
} else {
setStateInternal(LifecycleState.STARTED, null, false);
}
}
</code></pre></li>
</ol>
<p>在真正启动容器之前需要做2种检查:</p>
<p>如果当前容器已经处于启动过程(即容器状态为LifecycleState.STARTING_PREP、LifecycleState.STARTING、LifecycleState.STARTED)中,则会产生并且用日志记录LifecycleException异常并退出。<br>如果容器依然处于LifecycleState.NEW状态,则在启动之前,首先确保初始化完毕。</p>
<p>启动容器完毕后,需要做1种检查:<br>即如果容器启动异常导致容器进入LifecycleState.FAILED或者LifecycleState.MUST_STOP状态,则需要调用stop方法停止容器。</p>
<p>以StandardService为例,其startInternal的实现:</p>
<pre><code>protected void startInternal() throws LifecycleException {
if(log.isInfoEnabled())
log.info(sm.getString(&quot;standardService.start.name&quot;, this.name));
setState(LifecycleState.STARTING);//将自身状态更改为LifecycleState.STARTING;
// Start our defined Container first
if (container != null) {
synchronized (container) {
container.start();//调用子容器Service的start方法启动子容器。
}
}
synchronized (executors) {
for (Executor executor: executors) {
executor.start();
}
}
// Start our defined Connectors second
synchronized (connectorsLock) {
for (Connector connector: connectors) {
try {
// If it has already failed, don&apos;t try and start it
if (connector.getState() != LifecycleState.FAILED) {
connector.start();
}
} catch (Exception e) {
log.error(sm.getString(
&quot;standardService.connector.startFailed&quot;,
connector), e);
}
}
}
}
</code></pre><p>除了初始化、启动外,各个容器还有停止和销毁的生命周期,其原理与初始化、启动类似。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>Tomcat通过将内部所有组件都抽象为容器,为容器提供统一的生命周期管理,各个子容器只需要关心各自的具体实现,这便于Tomcat以后扩展更多的容器。</p>
]]></content>
<summary type="html">
&lt;p&gt;&lt;strong&gt;想必大家都知道,从server.xml文件解析出来的各个对象都是容器,比如:Server、Service、Connector等。这些容器都具有新建、初始化完成、启动、停止、失败、销毁等状态。Tomcat的实现机制是通过实现org.apache.catalina.Lifecycle接口来管理。&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id=&quot;Tomcat–Lifecycle接口&quot;&gt;&lt;a href=&quot;#Tomcat–Lifecycle接口&quot; class=&quot;headerlink&quot; title=&quot;Tomcat–Lifecycle接口&quot;&gt;&lt;/a&gt;Tomcat–Lifecycle接口&lt;/h2&gt;&lt;p&gt;定义了容器生命周期、容器状态转换及容器状态迁移事件的监听器注册和移除等主要接口。代码清单:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; public interface Lifecycle {
public static final String BEFORE_INIT_EVENT = &amp;quot;before_init&amp;quot;;
public static final String AFTER_INIT_EVENT = &amp;quot;after_init&amp;quot;;
public static final String START_EVENT = &amp;quot;start&amp;quot;;
public static final String BEFORE_START_EVENT = &amp;quot;before_start&amp;quot;;
public static final String AFTER_START_EVENT = &amp;quot;after_start&amp;quot;;
public static final String STOP_EVENT = &amp;quot;stop&amp;quot;;
public static final String BEFORE_STOP_EVENT = &amp;quot;before_stop&amp;quot;;
public static final String AFTER_STOP_EVENT = &amp;quot;after_stop&amp;quot;;
public static final String AFTER_DESTROY_EVENT = &amp;quot;after_destroy&amp;quot;;
public static final String BEFORE_DESTROY_EVENT = &amp;quot;before_destroy&amp;quot;;
public static final String PERIODIC_EVENT = &amp;quot;periodic&amp;quot;;
public static final String CONFIGURE_START_EVENT = &amp;quot;configure_start&amp;quot;;
public static final String CONFIGURE_STOP_EVENT = &amp;quot;configure_stop&amp;quot;;
public void addLifecycleListener(LifecycleListener listener);
public LifecycleListener[] findLifecycleListeners();
public void removeLifecycleListener(LifecycleListener listener);
public void init() throws LifecycleException;
public void start() throws LifecycleException;
public void stop() throws LifecycleException;
public void destroy() throws LifecycleException;
public LifecycleState getState();
public String getStateName();
public interface SingleUse {
}
}
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;其中,最重要的方法时start和stop方法。父组件通过这两个方法来启动/关闭该组件。addLifecycleListener,findLifecycleListeners,removeLifecycleListener三个方法用于向组件注册/查找/删除监听器。当事件发生时,会触发监听器。接口中还定义了相关事件。&lt;/p&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>Tomcat源码学习(五)-- Tomcat_7.0.70 类加载体系分析</title>
<link href="http://zhengweishan.oschina.io/2017/02/09/%EF%BC%88%E4%BA%94%EF%BC%89Tomcat_7.0.70%E7%B1%BB%E5%8A%A0%E8%BD%BD%E4%BD%93%E7%B3%BB/"/>
<id>http://zhengweishan.oschina.io/2017/02/09/(五)Tomcat_7.0.70类加载体系/</id>
<published>2017-02-08T16:00:00.000Z</published>
<updated>2017-03-01T09:01:05.987Z</updated>
<content type="html"><![CDATA[<h2 id="1、前言"><a href="#1、前言" class="headerlink" title="1、前言"></a>1、前言</h2><p>Tomcat遵循J2EE规范,实现了Web容器。Java虚拟机有自己的一套类加载体系,同样Tomcat也有自己的一套类加载体系。</p>
<h2 id="2、概述"><a href="#2、概述" class="headerlink" title="2、概述"></a>2、概述</h2><p>首先简单介绍下Java虚拟机的主要的类加载器:</p>
<p><img src="http://i.imgur.com/FjDnfWq.png" alt=""></p>
<ol>
<li><p>启动类加载器(bootstrap classloader)</p>
<p> 它用来加载 Java 的核心库,是用原生代码(本地代码,与平台有关)来实现的,并不继承自java.lang.ClassLoader。这个类加载器负责将存放在<java_home>\lib目录中的,或者被-Xbootclasspath参数所指定的路径中的,并且是虚拟机识加的(仅按照文件名识别,如rt.jar,名字不符合的类库即使放在lib目录中也不会被加载)类库加载到虚拟机内存中。启动类加载器无法被Java程序直接引用。</java_home></p>
</li>
<li><p>扩展类加载器(extensions classloader)</p>
<p> 扩展类加载器是由 Sun 的 ExtClassLoader(sun.misc.Launcher$ExtClassLoader) 实现的。它负责将 &lt; Java_Runtime_Home &gt;/lib/ext 或者由系统变量java.ext.dir 指定位置中的类库加载到内存中</p>
</li>
<li><p>应用程序类加载器(application classloader)</p>
<p> 系统类加载器是由 Sun 的 AppClassLoader(sun.misc.Launcher$AppClassLoader)实现的,由于这个类加载器是ClassLoader中getSystemClassLoader()方法的返回值,所以一般也称它为系统类加载器。它根据 Java 应用的类路径(CLASSPATH)来加载 Java 类。开发者可以直接使用这个类加载器,如果应用程序中没有自定义过自己的类加载器,一般情况下这个就是程序默认的类加载器。</p>
</li>
<li><p>用户自定义的类装载器 </p>
<p> 用户自定义的类装载器是普通的Java对象,它的类必须派生自java.lang.ClassLoader类。ClassLoader中定义的方法为程序为程序提供了访问类装载器机制的接口。此外,对于每一个被装载的类型,Java虚拟机都会为它创建一个java.lang.Class类的实例来代表该类型。和所有其它对象一样,用户自定义的类装载器以有Class类的实例都放在内存中的堆区,而装载的类型信息则都放在方法区。</p>
</li>
</ol>
<a id="more"></a>
<p>然后在来一张图简要说明Tomcat的类加载体系(图画的不好):</p>
<p><img src="http://i.imgur.com/9MPidXk.png" alt=""></p>
<ul>
<li>ClassLoader:Java提供的类加载器抽象类,用户自定义的类加载器需要继承实现</li>
<li>commonLoader:Tomcat最基本的类加载器,加载路径中的class可以被Tomcat容器本身以及各个Webapp访问</li>
<li>catalinaLoader:Tomcat容器私有的类加载器,加载路径中的class对于Webapp不可见</li>
<li>sharedLoader:各个Webapp共享的类加载器,加载路径中的class对于所有Webapp可见,但是对于Tomcat容器不可见</li>
<li><p>WebappClassLoader:各个Webapp私有的类加载器,加载路径中的class只对当前Webapp可见</p>
<h2 id="3、分析"><a href="#3、分析" class="headerlink" title="3、分析"></a>3、分析</h2><p>commonLoader、catalinaLoader和sharedLoader在Tomcat容器初始化的一开始,即调用Bootstrap的init方法时创建。catalinaLoader会被设置为Tomcat主线程的线程上下文类加载器,并且使用catalinaLoader加载Tomcat容器自身容器下的class。Bootstrap的init方法的部分代码如下:</p>
<p> /**</p>
<ul>
<li><p>Initialize daemon.<br>*/<br>public void init()<br> throws Exception<br>{<br> setCatalinaHome();<br> setCatalinaBase();</p>
<p> initClassLoaders();</p>
<p> Thread.currentThread().setContextClassLoader(catalinaLoader);</p>
<p> SecurityClassLoad.securityClassLoad(catalinaLoader);<br> …..<br>}</p>
</li>
</ul>
</li>
</ul>
<p>initClassLoaders方法:</p>
<pre><code>private void initClassLoaders() {
try {
commonLoader = createClassLoader(&quot;common&quot;, null);
if( commonLoader == null ) {
// no config file, default to this loader - we might be in a &apos;single&apos; env.
commonLoader=this.getClass().getClassLoader();
}
catalinaLoader = createClassLoader(&quot;server&quot;, commonLoader);
sharedLoader = createClassLoader(&quot;shared&quot;, commonLoader);
} catch (Throwable t) {
handleThrowable(t);
log.error(&quot;Class loader creation threw exception&quot;, t);
System.exit(1);
}
}
</code></pre><p>创建类加载器的createClassLoader方法的实现:</p>
<pre><code>private ClassLoader createClassLoader(String name, ClassLoader parent)
throws Exception {
String value = CatalinaProperties.getProperty(name + &quot;.loader&quot;);
if ((value == null) || (value.equals(&quot;&quot;)))
return parent;
value = replace(value);
List&lt;Repository&gt; repositories = new ArrayList&lt;Repository&gt;();
StringTokenizer tokenizer = new StringTokenizer(value, &quot;,&quot;);
while (tokenizer.hasMoreElements()) {
String repository = tokenizer.nextToken().trim();
if (repository.length() == 0) {
continue;
}
// Check for a JAR URL repository
try {
@SuppressWarnings(&quot;unused&quot;)
URL url = new URL(repository);
repositories.add(
new Repository(repository, RepositoryType.URL));
continue;
} catch (MalformedURLException e) {
// Ignore
}
// Local repository
if (repository.endsWith(&quot;*.jar&quot;)) {
repository = repository.substring
(0, repository.length() - &quot;*.jar&quot;.length());
repositories.add(
new Repository(repository, RepositoryType.GLOB));
} else if (repository.endsWith(&quot;.jar&quot;)) {
repositories.add(
new Repository(repository, RepositoryType.JAR));
} else {
repositories.add(
new Repository(repository, RepositoryType.DIR));
}
}
return ClassLoaderFactory.createClassLoader(repositories, parent);
}
</code></pre><p>createClassLoader最终使用ClassLoaderFactory.createClassLoader(locations, types, parent)方法创建ClassLoader。</p>
<p>我们在看SecurityClassLoad.securityClassLoad(catalinaLoader);</p>
<pre><code> public static void securityClassLoad(ClassLoader loader)
throws Exception {
if( System.getSecurityManager() == null ){
return;
}
loadCorePackage(loader);
loadCoyotePackage(loader);
loadLoaderPackage(loader);
loadRealmPackage(loader);
loadServletsPackage(loader);
loadSessionPackage(loader);
loadUtilPackage(loader);
loadValvesPackage(loader);
loadJavaxPackage(loader);
loadConnectorPackage(loader);
loadTomcatPackage(loader);
}
</code></pre><p>securityClassLoad方法主要加载Tomcat容器所需的class,包括:</p>
<ul>
<li>Tomcat核心class,即org.apache.catalina.core路径下的class;</li>
<li>org.apache.catalina.loader.WebappClassLoader$PrivilegedFindResourceByName</li>
<li>Tomcat有关session的class,即org.apache.catalina.session路径下的class</li>
<li>Tomcat工具类的class,即org.apache.catalina.util路径下的class</li>
<li>javax.servlet.http.Cookie</li>
<li>Tomcat处理请求的class,即org.apache.catalina.connector路径下的class</li>
<li>Tomcat其它工具类的class,也是org.apache.catalina.util路径下的class</li>
</ul>
<p>我们以加载Tomcat核心class的loadCorePackage方法为例,查看其实现:</p>
<pre><code>private static final void loadCorePackage(ClassLoader loader)
throws Exception {
final String basePackage = &quot;org.apache.catalina.core.&quot;;
loader.loadClass
(basePackage +
&quot;AccessLogAdapter&quot;);
loader.loadClass
(basePackage +
&quot;ApplicationContextFacade$1&quot;);
loader.loadClass
(basePackage +
&quot;ApplicationDispatcher$PrivilegedForward&quot;);
loader.loadClass
(basePackage +
&quot;ApplicationDispatcher$PrivilegedInclude&quot;);
loader.loadClass
(basePackage +
&quot;AsyncContextImpl&quot;);
loader.loadClass
(basePackage +
&quot;AsyncContextImpl$DebugException&quot;);
loader.loadClass
(basePackage +
&quot;AsyncContextImpl$1&quot;);
loader.loadClass
(basePackage +
&quot;AsyncListenerWrapper&quot;);
loader.loadClass
(basePackage +
&quot;ContainerBase$PrivilegedAddChild&quot;);
loader.loadClass
(basePackage +
&quot;DefaultInstanceManager$1&quot;);
loader.loadClass
(basePackage +
&quot;DefaultInstanceManager$2&quot;);
loader.loadClass
(basePackage +
&quot;DefaultInstanceManager$3&quot;);
loader.loadClass
(basePackage +
&quot;DefaultInstanceManager$AnnotationCacheEntry&quot;);
loader.loadClass
(basePackage +
&quot;DefaultInstanceManager$AnnotationCacheEntryType&quot;);
loader.loadClass
(basePackage +
&quot;ApplicationHttpRequest$AttributeNamesEnumerator&quot;);
}
</code></pre><p>至此为止,我们还没有看到WebappClassLoader。启动StandardContext的时候会创建WebappLoader,StandardContext的方法startInternal的部分代码如下:</p>
<pre><code> protected synchronized void startInternal() throws LifecycleException {
......
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
}
......
if ((loader != null) &amp;&amp; (loader instanceof Lifecycle))
((Lifecycle) loader).start();
// 省略后边的代码
}
</code></pre><p>从上面代码看到最后会调用WebappLoader的start方法:</p>
<pre><code>public final synchronized void start() throws LifecycleException {
if (LifecycleState.STARTING_PREP.equals(state) || LifecycleState.STARTING.equals(state) ||
LifecycleState.STARTED.equals(state)) {
if (log.isDebugEnabled()) {
Exception e = new LifecycleException();
log.debug(sm.getString(&quot;lifecycleBase.alreadyStarted&quot;, toString()), e);
} else if (log.isInfoEnabled()) {
log.info(sm.getString(&quot;lifecycleBase.alreadyStarted&quot;, toString()));
}
return;
}
if (state.equals(LifecycleState.NEW)) {
init();
} else if (state.equals(LifecycleState.FAILED)) {
stop();
} else if (!state.equals(LifecycleState.INITIALIZED) &amp;&amp;
!state.equals(LifecycleState.STOPPED)) {
invalidTransition(Lifecycle.BEFORE_START_EVENT);
}
setStateInternal(LifecycleState.STARTING_PREP, null, false);
try {
startInternal();//start再次调用了startInternal方法(WebappLoader中的方法)
} catch (Throwable t) {
// This is an &apos;uncontrolled&apos; failure so put the component into the
// FAILED state and throw an exception.
ExceptionUtils.handleThrowable(t);
setStateInternal(LifecycleState.FAILED, null, false);
throw new LifecycleException(sm.getString(&quot;lifecycleBase.startFail&quot;, toString()), t);
}
if (state.equals(LifecycleState.FAILED)) {
// This is a &apos;controlled&apos; failure. The component put itself into the
// FAILED state so call stop() to complete the clean-up.
stop();
} else if (!state.equals(LifecycleState.STARTING)) {
// Shouldn&apos;t be necessary but acts as a check that sub-classes are
// doing what they are supposed to.
invalidTransition(Lifecycle.AFTER_START_EVENT);
} else {
setStateInternal(LifecycleState.STARTED, null, false);
}
}
</code></pre><p>start又调用了startInternal方法,startInternal的实现如下:</p>
<pre><code>protected void startInternal() throws LifecycleException {
if (log.isDebugEnabled())
log.debug(sm.getString(&quot;webappLoader.starting&quot;));
if (container.getResources() == null) {
log.info(&quot;No resources for &quot; + container);
setState(LifecycleState.STARTING);
return;
}
// Register a stream handler factory for the JNDI protocol
URLStreamHandlerFactory streamHandlerFactory =
DirContextURLStreamHandlerFactory.getInstance();
if (first) {
first = false;
try {
URL.setURLStreamHandlerFactory(streamHandlerFactory);
} catch (Exception e) {
// Log and continue anyway, this is not critical
log.error(&quot;Error registering jndi stream handler&quot;, e);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This is likely a dual registration
log.info(&quot;Dual registration of jndi stream handler: &quot;
+ t.getMessage());
}
}
// Construct a class loader based on our current repositories list
try {
classLoader = createClassLoader();
classLoader.setResources(container.getResources());
classLoader.setDelegate(this.delegate);
classLoader.setSearchExternalFirst(searchExternalFirst);
if (container instanceof StandardContext) {
classLoader.setAntiJARLocking(
((StandardContext) container).getAntiJARLocking());
classLoader.setClearReferencesRmiTargets(
((StandardContext) container).getClearReferencesRmiTargets());
classLoader.setClearReferencesStatic(
((StandardContext) container).getClearReferencesStatic());
classLoader.setClearReferencesStopThreads(
((StandardContext) container).getClearReferencesStopThreads());
classLoader.setClearReferencesStopTimerThreads(
((StandardContext) container).getClearReferencesStopTimerThreads());
classLoader.setClearReferencesHttpClientKeepAliveThread(
((StandardContext) container).getClearReferencesHttpClientKeepAliveThread());
}
for (int i = 0; i &lt; repositories.length; i++) {
classLoader.addRepository(repositories[i]);
}
// Configure our repositories
setRepositories();
setClassPath();
setPermissions();
((Lifecycle) classLoader).start();
// Binding the Webapp class loader to the directory context
DirContextURLStreamHandler.bind(classLoader,
this.container.getResources());
StandardContext ctx=(StandardContext)container;
String contextName = ctx.getName();
if (!contextName.startsWith(&quot;/&quot;)) {
contextName = &quot;/&quot; + contextName;
}
ObjectName cloname = new ObjectName
(MBeanUtils.getDomain(ctx) + &quot;:type=WebappClassLoader,context=&quot;
+ contextName + &quot;,host=&quot; + ctx.getParent().getName());
Registry.getRegistry(null, null)
.registerComponent(classLoader, cloname, null);
} catch (Throwable t) {
t = ExceptionUtils.unwrapInvocationTargetException(t);
ExceptionUtils.handleThrowable(t);
log.error( &quot;LifecycleException &quot;, t );
throw new LifecycleException(&quot;start: &quot;, t);
}
setState(LifecycleState.STARTING);
}
</code></pre><p>最后我们看看createClassLoader的实现:</p>
<pre><code> private WebappClassLoaderBase createClassLoader()
throws Exception {
Class&lt;?&gt; clazz = Class.forName(loaderClass);
WebappClassLoaderBase classLoader = null;
if (parentClassLoader == null) {
parentClassLoader = container.getParentClassLoader();
}
Class&lt;?&gt;[] argTypes = { ClassLoader.class };
Object[] args = { parentClassLoader };
Constructor&lt;?&gt; constr = clazz.getConstructor(argTypes);
classLoader = (WebappClassLoaderBase) constr.newInstance(args);
return classLoader;
}
</code></pre><p>至此Tomcat类加载完毕。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、前言&quot;&gt;&lt;a href=&quot;#1、前言&quot; class=&quot;headerlink&quot; title=&quot;1、前言&quot;&gt;&lt;/a&gt;1、前言&lt;/h2&gt;&lt;p&gt;Tomcat遵循J2EE规范,实现了Web容器。Java虚拟机有自己的一套类加载体系,同样Tomcat也有自己的一套类加载体系。&lt;/p&gt;
&lt;h2 id=&quot;2、概述&quot;&gt;&lt;a href=&quot;#2、概述&quot; class=&quot;headerlink&quot; title=&quot;2、概述&quot;&gt;&lt;/a&gt;2、概述&lt;/h2&gt;&lt;p&gt;首先简单介绍下Java虚拟机的主要的类加载器:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/FjDnfWq.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;p&gt;启动类加载器(bootstrap classloader)&lt;/p&gt;
&lt;p&gt; 它用来加载 Java 的核心库,是用原生代码(本地代码,与平台有关)来实现的,并不继承自java.lang.ClassLoader。这个类加载器负责将存放在&lt;JAVA_HOME&gt;\lib目录中的,或者被-Xbootclasspath参数所指定的路径中的,并且是虚拟机识加的(仅按照文件名识别,如rt.jar,名字不符合的类库即使放在lib目录中也不会被加载)类库加载到虚拟机内存中。启动类加载器无法被Java程序直接引用。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;扩展类加载器(extensions classloader)&lt;/p&gt;
&lt;p&gt; 扩展类加载器是由 Sun 的 ExtClassLoader(sun.misc.Launcher$ExtClassLoader) 实现的。它负责将 &amp;lt; Java_Runtime_Home &amp;gt;/lib/ext 或者由系统变量java.ext.dir 指定位置中的类库加载到内存中&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;应用程序类加载器(application classloader)&lt;/p&gt;
&lt;p&gt; 系统类加载器是由 Sun 的 AppClassLoader(sun.misc.Launcher$AppClassLoader)实现的,由于这个类加载器是ClassLoader中getSystemClassLoader()方法的返回值,所以一般也称它为系统类加载器。它根据 Java 应用的类路径(CLASSPATH)来加载 Java 类。开发者可以直接使用这个类加载器,如果应用程序中没有自定义过自己的类加载器,一般情况下这个就是程序默认的类加载器。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;用户自定义的类装载器 &lt;/p&gt;
&lt;p&gt; 用户自定义的类装载器是普通的Java对象,它的类必须派生自java.lang.ClassLoader类。ClassLoader中定义的方法为程序为程序提供了访问类装载器机制的接口。此外,对于每一个被装载的类型,Java虚拟机都会为它创建一个java.lang.Class类的实例来代表该类型。和所有其它对象一样,用户自定义的类装载器以有Class类的实例都放在内存中的堆区,而装载的类型信息则都放在方法区。&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>Tommcat源码学习(四)--Tomcat_7.0.70 server.xml文件的加载与解析</title>
<link href="http://zhengweishan.oschina.io/2017/02/08/%EF%BC%88%E5%9B%9B%EF%BC%89Tomcat_7.0.70%20server.xml%E6%96%87%E4%BB%B6%E7%9A%84%E5%8A%A0%E8%BD%BD%E4%B8%8E%E8%A7%A3%E6%9E%90/"/>
<id>http://zhengweishan.oschina.io/2017/02/08/(四)Tomcat_7.0.70 server.xml文件的加载与解析/</id>
<published>2017-02-07T16:00:00.000Z</published>
<updated>2017-03-01T08:54:07.663Z</updated>
<content type="html"><![CDATA[<h1 id="1、文件的加载"><a href="#1、文件的加载" class="headerlink" title="1、文件的加载"></a>1、文件的加载</h1><p>Bootstrap的load方法是加载Tomcat的server.xml的入口,load方法实际通过反射调用catalinaDaemon(类型为Catalina)的load方法:</p>
<pre><code>/**
* Load daemon.
*/
private void load(String[] arguments)
throws Exception {
// Call the load() method
String methodName = &quot;load&quot;;
Object param[];
Class&lt;?&gt; paramTypes[];
if (arguments==null || arguments.length==0) {
paramTypes = null;
param = null;
} else {
paramTypes = new Class[1];
paramTypes[0] = arguments.getClass();
param = new Object[1];
param[0] = arguments;
}
Method method =
catalinaDaemon.getClass().getMethod(methodName, paramTypes);//通过反射机制调用Catalina类的load方法。
if (log.isDebugEnabled())
log.debug(&quot;Calling startup class &quot; + method);
method.invoke(catalinaDaemon, param);
}
</code></pre><a id="more"></a>
<p>Catalina类的load方法:</p>
<pre><code> /*
* Load using arguments
*/
public void load(String args[]) {
try {
if (arguments(args)) {
load();//调用自身的load方法
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
/**
* Start a new server instance.
*/
public void load() {
long t1 = System.nanoTime();
initDirs(); //用于对catalina.home和catalina.base的一些检查工作
// Before digester - it may be needed
initNaming();//给系统设置java.naming.factory.url.pkgs和java.naming.factory.initial
// Create and execute our Digester
Digester digester = createStartDigester();//实例化Digester
InputSource inputSource = null;
InputStream inputStream = null;
File file = null;
try {
try {
file = configFile();//获取conf/server.xml配置文件
inputStream = new FileInputStream(file);获取conf/server.xml配置文件输入流
inputSource = new InputSource(file.toURI().toURL().toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(&quot;catalina.configFail&quot;, file), e);
}
}
if (inputStream == null) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream(getConfigFile());
inputSource = new InputSource
(getClass().getClassLoader()
.getResource(getConfigFile()).toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(&quot;catalina.configFail&quot;,
getConfigFile()), e);
}
}
}
// This should be included in catalina.jar
// Alternative: don&apos;t bother with xml, just create it manually.
if( inputStream==null ) {
try {
inputStream = getClass().getClassLoader()
.getResourceAsStream(&quot;server-embed.xml&quot;);
inputSource = new InputSource
(getClass().getClassLoader()
.getResource(&quot;server-embed.xml&quot;).toString());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(&quot;catalina.configFail&quot;,
&quot;server-embed.xml&quot;), e);
}
}
}
if (inputStream == null || inputSource == null) {
if (file == null) {
log.warn(sm.getString(&quot;catalina.configFail&quot;,
getConfigFile() + &quot;] or [server-embed.xml]&quot;));
} else {
log.warn(sm.getString(&quot;catalina.configFail&quot;,
file.getAbsolutePath()));
if (file.exists() &amp;&amp; !file.canRead()) {
log.warn(&quot;Permissions incorrect, read permission is not allowed on the file.&quot;);
}
}
return;
}
try {
inputSource.setByteStream(inputStream);//将FileInputStream封装为InputSource
digester.push(this);
digester.parse(inputSource);//调用Digester的parse方法进行解析
} catch (SAXParseException spe) {
log.warn(&quot;Catalina.start using &quot; + getConfigFile() + &quot;: &quot; +
spe.getMessage());
return;
} catch (Exception e) {
log.warn(&quot;Catalina.start using &quot; + getConfigFile() + &quot;: &quot; , e);
return;
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// Ignore
}
}
}
getServer().setCatalina(this);
// Stream redirection
initStreams();//initStreams对输出流、错误流重定向
// Start the new server
try {
getServer().init();//初始化server
} catch (LifecycleException e) {
if (Boolean.getBoolean(&quot;org.apache.catalina.startup.EXIT_ON_INIT_FAILURE&quot;)) {
throw new java.lang.Error(e);
} else {
log.error(&quot;Catalina.start&quot;, e);
}
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info(&quot;Initialization processed in &quot; + ((t2 - t1) / 1000000) + &quot; ms&quot;);
}
}
</code></pre><p>下面开始分析整个过程:</p>
<h2 id="1-1、initDirs()方法用于对catalina-home和catalina-base的一些检查工作"><a href="#1-1、initDirs()方法用于对catalina-home和catalina-base的一些检查工作" class="headerlink" title="1.1、initDirs()方法用于对catalina.home和catalina.base的一些检查工作"></a>1.1、initDirs()方法用于对catalina.home和catalina.base的一些检查工作</h2><pre><code>protected void initDirs() {
String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
if (catalinaHome == null) {
// Backwards compatibility patch for J2EE RI 1.3
String j2eeHome = System.getProperty(&quot;com.sun.enterprise.home&quot;);
if (j2eeHome != null) {
catalinaHome=System.getProperty(&quot;com.sun.enterprise.home&quot;);
} else if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) {
catalinaHome = System.getProperty(Globals.CATALINA_BASE_PROP);
}
}
// last resort - for minimal/embedded cases.
if(catalinaHome==null) {
catalinaHome=System.getProperty(&quot;user.dir&quot;);
}
if (catalinaHome != null) {
File home = new File(catalinaHome);
if (!home.isAbsolute()) {
try {
catalinaHome = home.getCanonicalPath();
} catch (IOException e) {
catalinaHome = home.getAbsolutePath();
}
}
System.setProperty(Globals.CATALINA_HOME_PROP, catalinaHome);
}
if (System.getProperty(Globals.CATALINA_BASE_PROP) == null) {
System.setProperty(Globals.CATALINA_BASE_PROP,
catalinaHome);
} else {
String catalinaBase = System.getProperty(Globals.CATALINA_BASE_PROP);
File base = new File(catalinaBase);
if (!base.isAbsolute()) {
try {
catalinaBase = base.getCanonicalPath();
} catch (IOException e) {
catalinaBase = base.getAbsolutePath();
}
}
System.setProperty(Globals.CATALINA_BASE_PROP, catalinaBase);
}
String temp = System.getProperty(&quot;java.io.tmpdir&quot;);
if (temp == null || (!(new File(temp)).exists())
|| (!(new File(temp)).isDirectory())) {
log.error(sm.getString(&quot;embedded.notmp&quot;, temp));
}
}
</code></pre><h2 id="1-2、initNaming-方法给系统设置java-naming-factory-url-pkgs和java-naming-factory-initial"><a href="#1-2、initNaming-方法给系统设置java-naming-factory-url-pkgs和java-naming-factory-initial" class="headerlink" title="1.2、initNaming()方法给系统设置java.naming.factory.url.pkgs和java.naming.factory.initial"></a>1.2、initNaming()方法给系统设置java.naming.factory.url.pkgs和java.naming.factory.initial</h2><pre><code> protected void initNaming() {
// Setting additional variables
if (!useNaming) {
log.info( &quot;Catalina naming disabled&quot;);
System.setProperty(&quot;catalina.useNaming&quot;, &quot;false&quot;);
} else {
System.setProperty(&quot;catalina.useNaming&quot;, &quot;true&quot;);
String value = &quot;org.apache.naming&quot;;
String oldValue =
System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
if (oldValue != null) {
value = value + &quot;:&quot; + oldValue;
}
System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
if( log.isDebugEnabled() ) {
log.debug(&quot;Setting naming prefix=&quot; + value);
}
value = System.getProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
if (value == null) {
System.setProperty
(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
&quot;org.apache.naming.java.javaURLContextFactory&quot;);
} else {
log.debug( &quot;INITIAL_CONTEXT_FACTORY already set &quot; + value );
}
}
}
</code></pre><p>在创建JNDI上下文时,使用Context.INITIAL <em> CONTEXT </em> FACTORY(”java.naming.factory.initial”)属性,来指定创建JNDI上下文的工厂类;Context.URL <em> PKG </em> PREFIXES(“java.naming.factory.url.pkgs”)用在查询url中包括scheme方法id时创建对应的JNDI上下文.</p>
<h2 id="1-3、createStartDigester-创建并配置将要用来启动的Digester实例,并且设置一些列Rule,具体映射到server-xml"><a href="#1-3、createStartDigester-创建并配置将要用来启动的Digester实例,并且设置一些列Rule,具体映射到server-xml" class="headerlink" title="1.3、createStartDigester()创建并配置将要用来启动的Digester实例,并且设置一些列Rule,具体映射到server.xml"></a>1.3、createStartDigester()创建并配置将要用来启动的Digester实例,并且设置一些列Rule,具体映射到server.xml</h2><pre><code>/**
* Create and configure the Digester we will be using for startup.
*/
protected Digester createStartDigester() {
long t1=System.currentTimeMillis();
// Initialize the digester
Digester digester = new Digester();
digester.setValidating(false);
digester.setRulesValidation(true);
HashMap&lt;Class&lt;?&gt;, List&lt;String&gt;&gt; fakeAttributes =
new HashMap&lt;Class&lt;?&gt;, List&lt;String&gt;&gt;();
ArrayList&lt;String&gt; attrs = new ArrayList&lt;String&gt;();
attrs.add(&quot;className&quot;);
fakeAttributes.put(Object.class, attrs);
digester.setFakeAttributes(fakeAttributes);
digester.setUseContextClassLoader(true);
// Configure the actions we will be using
digester.addObjectCreate(&quot;Server&quot;,
&quot;org.apache.catalina.core.StandardServer&quot;,
&quot;className&quot;);
digester.addSetProperties(&quot;Server&quot;);
digester.addSetNext(&quot;Server&quot;,
&quot;setServer&quot;,
&quot;org.apache.catalina.Server&quot;);
digester.addObjectCreate(&quot;Server/GlobalNamingResources&quot;,
&quot;org.apache.catalina.deploy.NamingResources&quot;);
digester.addSetProperties(&quot;Server/GlobalNamingResources&quot;);
digester.addSetNext(&quot;Server/GlobalNamingResources&quot;,
&quot;setGlobalNamingResources&quot;,
&quot;org.apache.catalina.deploy.NamingResources&quot;);
digester.addObjectCreate(&quot;Server/Listener&quot;,
null, // MUST be specified in the element
&quot;className&quot;);
digester.addSetProperties(&quot;Server/Listener&quot;);
digester.addSetNext(&quot;Server/Listener&quot;,
&quot;addLifecycleListener&quot;,
&quot;org.apache.catalina.LifecycleListener&quot;);
digester.addObjectCreate(&quot;Server/Service&quot;,
&quot;org.apache.catalina.core.StandardService&quot;,
&quot;className&quot;);
digester.addSetProperties(&quot;Server/Service&quot;);
digester.addSetNext(&quot;Server/Service&quot;,
&quot;addService&quot;,
&quot;org.apache.catalina.Service&quot;);
digester.addObjectCreate(&quot;Server/Service/Listener&quot;,
null, // MUST be specified in the element
&quot;className&quot;);
digester.addSetProperties(&quot;Server/Service/Listener&quot;);
digester.addSetNext(&quot;Server/Service/Listener&quot;,
&quot;addLifecycleListener&quot;,
&quot;org.apache.catalina.LifecycleListener&quot;);
//Executor
digester.addObjectCreate(&quot;Server/Service/Executor&quot;,
&quot;org.apache.catalina.core.StandardThreadExecutor&quot;,
&quot;className&quot;);
digester.addSetProperties(&quot;Server/Service/Executor&quot;);
digester.addSetNext(&quot;Server/Service/Executor&quot;,
&quot;addExecutor&quot;,
&quot;org.apache.catalina.Executor&quot;);
digester.addRule(&quot;Server/Service/Connector&quot;,
new ConnectorCreateRule());
digester.addRule(&quot;Server/Service/Connector&quot;,
new SetAllPropertiesRule(new String[]{&quot;executor&quot;}));
digester.addSetNext(&quot;Server/Service/Connector&quot;,
&quot;addConnector&quot;,
&quot;org.apache.catalina.connector.Connector&quot;);
digester.addObjectCreate(&quot;Server/Service/Connector/Listener&quot;,
null, // MUST be specified in the element
&quot;className&quot;);
digester.addSetProperties(&quot;Server/Service/Connector/Listener&quot;);
digester.addSetNext(&quot;Server/Service/Connector/Listener&quot;,
&quot;addLifecycleListener&quot;,
&quot;org.apache.catalina.LifecycleListener&quot;);
// Add RuleSets for nested elements
digester.addRuleSet(new NamingRuleSet(&quot;Server/GlobalNamingResources/&quot;));
digester.addRuleSet(new EngineRuleSet(&quot;Server/Service/&quot;));
digester.addRuleSet(new HostRuleSet(&quot;Server/Service/Engine/&quot;));
digester.addRuleSet(new ContextRuleSet(&quot;Server/Service/Engine/Host/&quot;));
addClusterRuleSet(digester, &quot;Server/Service/Engine/Host/Cluster/&quot;);
digester.addRuleSet(new NamingRuleSet(&quot;Server/Service/Engine/Host/Context/&quot;));
// When the &apos;engine&apos; is found, set the parentClassLoader.
digester.addRule(&quot;Server/Service/Engine&quot;,
new SetParentClassLoaderRule(parentClassLoader));
addClusterRuleSet(digester, &quot;Server/Service/Engine/Cluster/&quot;);
long t2=System.currentTimeMillis();
if (log.isDebugEnabled()) {
log.debug(&quot;Digester for server.xml created &quot; + ( t2-t1 ));
}
return (digester);
}
</code></pre><p>从上面的代码可以看出:首先创建Digester,Digester继承了DefaultHandler,而DefaultHandler默认实现了ContentHander、DTDHander、ErrorHandler及EntityResolver 这4个接口,代码如下:</p>
<pre><code>public class DefaultHandler implements EntityResolver, DTDHandler, ContentHandler, ErrorHandler
</code></pre><p>通过源码可以发现DefaultHandler的所有实现都是空实现,所以解析还需要Digester。(具体分析后面在说)。</p>
<h2 id="1-4、configFile-获取配置文件conf-server-xml,并使用FileInputStream获取conf-server-xml配置文件输入流"><a href="#1-4、configFile-获取配置文件conf-server-xml,并使用FileInputStream获取conf-server-xml配置文件输入流" class="headerlink" title="1.4、configFile()获取配置文件conf/server.xml,并使用FileInputStream获取conf/server.xml配置文件输入流"></a>1.4、configFile()获取配置文件conf/server.xml,并使用FileInputStream获取conf/server.xml配置文件输入流</h2><pre><code>/**
* Return a File object representing our configuration file.
*/
protected File configFile() {
File file = new File(configFile);
if (!file.isAbsolute()) {
file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), configFile);
}
return (file);
}
</code></pre><h2 id="1-5、将FileInputStream封装为InputSource,并且调用Digester的parse方法进行解析"><a href="#1-5、将FileInputStream封装为InputSource,并且调用Digester的parse方法进行解析" class="headerlink" title="1.5、将FileInputStream封装为InputSource,并且调用Digester的parse方法进行解析"></a>1.5、将FileInputStream封装为InputSource,并且调用Digester的parse方法进行解析</h2><pre><code>inputSource.setByteStream(inputStream);
digester.push(this);
digester.parse(inputSource);
</code></pre><h2 id="1-6、initStreams-对输出流、错误流重定向"><a href="#1-6、initStreams-对输出流、错误流重定向" class="headerlink" title="1.6、initStreams()对输出流、错误流重定向"></a>1.6、initStreams()对输出流、错误流重定向</h2><pre><code> protected void initStreams() {
// Replace System.out and System.err with a custom PrintStream
System.setOut(new SystemLogHandler(System.out));
System.setErr(new SystemLogHandler(System.err));
}
</code></pre><h2 id="1-7、初始化server"><a href="#1-7、初始化server" class="headerlink" title="1.7、初始化server"></a>1.7、初始化server</h2><pre><code>// Start the new server
try {
getServer().init();
} catch (LifecycleException e) {
if (Boolean.getBoolean(&quot;org.apache.catalina.startup.EXIT_ON_INIT_FAILURE&quot;)) {
throw new java.lang.Error(e);
} else {
log.error(&quot;Catalina.start&quot;, e);
}
}
</code></pre><h1 id="2、文件的解析"><a href="#2、文件的解析" class="headerlink" title="2、文件的解析"></a>2、文件的解析</h1><p>当加载server.xml配置文件到内存后,开始对XML文件中的内容进行解析,主要包含两个步骤:</p>
<ol>
<li>构造server.xml的规则,这些规则即可以用于构造Tomcat内部的容器(如StandardServer,StandardService等),也可以对server.xml进行合法性检查。如果server.xml不符合Tomcat内置的规则,在解析时将抛出异常,进而导致Tomcat无法启动。</li>
<li>使用SAX解析server.xml,边解析边应用规则,最终使用server.xml中的配置构建好Tomcat所需的各种容器。</li>
</ol>
<p><img src="http://i.imgur.com/0G69ss1.jpg" alt=""></p>
<p>Tomcat将server.xml文件中的所有元素上的属性都抽象为Rule,以Server元素为例,在内存中对应Server实例,Server实例的属性值就来自于Server元素的属性值。通过对规则(Rule)的应用,最终改变Server实例的属性值。Rule是一个抽象类,其中定义了以下方法:</p>
<p><img src="http://i.imgur.com/5TROnzW.png" alt=""></p>
<ul>
<li>getDigester:获取Digester实例;</li>
<li>setDigester:设置Digester实例;</li>
<li>getNamespaceURI:获取Rule所在的相对命名空间URI;</li>
<li>setNamespaceURI:设置Rule所在的相对命名空间URI;</li>
<li>begin(String namespace, String name, Attributes attributes):此方法在遇到一个匹配的XML元素的开头时被调用,如<server>;</server></li>
<li>body(String namespace, String name, String text):在遇到匹配XML元素的body时,此方法被调用,如进入标签内部时;</li>
<li>end(String namespace, String name):此方法在遇到一个匹配的XML元素的末尾时被调用。如:&lt; /Server&gt;;</li>
</ul>
<p>Rule目前有很多实现类,如:NodeCreateRule、AbsoluteOrderingRule、CallParamRule、ConnectorCreateRule等。下图展示了Rule的部分实现类:</p>
<p><img src="http://i.imgur.com/AU4umDE.png" alt=""></p>
<p>Tomcat使用SAX(Simple API for XML)解析XML:</p>
<p>SAX解析XML采用的是从上而下的基于事件驱动的解析方式,在解析过程中会视情况自动调用ContentHandler接口中的startDocument()、startElement()、characters()、endElement()、endDocument()等相关的方法。</p>
<p>由编译执行的结果分析:</p>
<ul>
<li>startDocument()方法只会在文档开始解析的时候被调用,每次解析只会调用一次。</li>
<li>startElement()方法每次在开始解析一个元素,即遇到元素标签开始的时候都会调用。</li>
<li>characters()方法也是在每次解析到元素标签携带的内容时都会调用,即使该元素标签的内容为空或换行。而且如果元素内嵌套元素,在父元素结束标签前, characters()方法会再次被调用,此处需要注意。</li>
<li>endElement()方法每次在结束解析一个元素,即遇到元素标签结束的时候都会调用。</li>
<li>endDocument()方法只会在文档解析结束的时候被调用,每次解析只会调用一次。</li>
</ul>
<p>使用SAX解析XML的好处:</p>
<ul>
<li>SAX 不用解析完整个文档</li>
<li>相比于 DOM 而言 SAX 是一种速度更快,更有效,占用内存更少的解析 XML 文件的方法</li>
<li>逐行扫描,可以做到边扫描边解析,因此 SAX 可以在解析文档的任意时刻停止解析</li>
</ul>
<p>由于SAX是基于事件驱动的,不用解析完整个文档,在按内容顺序解析文档过程中, SAX 会判断当前读到的字符是否符合 XML 文件语法中的某部分。如果符合某部分,则会触发事件。所谓触发事件,就是调用一些回调方法。在用 SAX 解析 xml 文档时候,在读取到文档开始和结束标签时候就会回调一个事件,在读取到其他节点与内容时候也会回调一个事件。在 SAX 接口中,事件源是 org.xml.sax 包中的 XMLReader ,它通过 parser() 方法来解析 XML 文档,并产生事件。事件处理器是 org.xml.sax 包中 ContentHander 、 DTDHander 、 ErrorHandler ,以及 EntityResolver 这4个接口:</p>
<ol>
<li>ContentHander ( XML 文档的开始与结束)setContentHandler(ContentHandler h) </li>
<li>DTDHander ( 处理 DTD 解析) setDTDHandler(DTDHandler h) </li>
<li>ErrorHandler ( 处理 XML 时产生的错误)setErrorHandler(ErrorHandler h) </li>
<li>EntityResolver (处理外部实体) setEntityResolver(EntityResolver e) </li>
</ol>
<p>回调方法一般都定义在ContentHandler接口中,上面已经对这些回调方法的加载顺序已经说了就不在介绍了。</p>
<p>使用 SAX 解析 XML 文件一般有以下五个步骤: </p>
<ol>
<li>创建一个 SAXParserFactory 对象; </li>
<li>调用 SAXParserFactory 中的 newSAXParser 方法创建一个 SAXParser 对象; </li>
<li>然后在调用 SAXParser 中的 getXMLReader 方法获取一个 XMLReader 对象;</li>
<li>实例化一个 DefaultHandler 对象;</li>
<li>连接事件源对象 XMLReader 到事件处理类 DefaultHandler 中;</li>
<li>调用 XMLReader 的 parse 方法从输入源中获取到的 xml 数据;</li>
<li>通过 DefaultHandler 返回我们需要的数据集合。</li>
</ol>
<p>我们通过源码可以发现DefaultHandler的所有实现都是空实现,所以解析还需要Digester自身,代码如下:</p>
<pre><code> @Override
public void startDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
saxLog.debug(&quot;startDocument()&quot;);
}
// ensure that the digester is properly configured, as
// the digester could be used as a SAX ContentHandler
// rather than via the parse() methods.
configure();
}
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
boolean debug = log.isDebugEnabled();
if (saxLog.isDebugEnabled()) {
saxLog.debug(&quot;startElement(&quot; + namespaceURI + &quot;,&quot; + localName + &quot;,&quot; +
qName + &quot;)&quot;);
}
// Parse system properties
list = updateAttributes(list);
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText);
bodyText = new StringBuilder();
// the actual element name is either in localName or qName, depending
// on whether the parser is namespace aware
String name = localName;
if ((name == null) || (name.length() &lt; 1)) {
name = qName;
}
// Compute the current matching rule
StringBuilder sb = new StringBuilder(match);
if (match.length() &gt; 0) {
sb.append(&apos;/&apos;);
}
sb.append(name);
match = sb.toString();
if (debug) {
log.debug(&quot; New match=&apos;&quot; + match + &quot;&apos;&quot;);
}
// Fire &quot;begin&quot; events for all relevant rules
List&lt;Rule&gt; rules = getRules().match(namespaceURI, match);
matches.push(rules);
if ((rules != null) &amp;&amp; (rules.size() &gt; 0)) {
for (int i = 0; i &lt; rules.size(); i++) {
try {
Rule rule = rules.get(i);
if (debug) {
log.debug(&quot; Fire begin() for &quot; + rule);
}
rule.begin(namespaceURI, name, list);
} catch (Exception e) {
log.error(&quot;Begin event threw exception&quot;, e);
throw createSAXException(e);
} catch (Error e) {
log.error(&quot;Begin event threw error&quot;, e);
throw e;
}
}
} else {
if (debug) {
log.debug(&quot; No rules found matching &apos;&quot; + match + &quot;&apos;.&quot;);
}
}
}
@Override
public void endDocument() throws SAXException {
if (saxLog.isDebugEnabled()) {
if (getCount() &gt; 1) {
saxLog.debug(&quot;endDocument(): &quot; + getCount() +
&quot; elements left&quot;);
} else {
saxLog.debug(&quot;endDocument()&quot;);
}
}
while (getCount() &gt; 1) {
pop();
}
// Fire &quot;finish&quot; events for all defined rules
Iterator&lt;Rule&gt; rules = getRules().rules().iterator();
while (rules.hasNext()) {
Rule rule = rules.next();
try {
rule.finish();
} catch (Exception e) {
log.error(&quot;Finish event threw exception&quot;, e);
throw createSAXException(e);
} catch (Error e) {
log.error(&quot;Finish event threw error&quot;, e);
throw e;
}
}
// Perform final cleanup
clear();
}
@Override
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
boolean debug = log.isDebugEnabled();
if (debug) {
if (saxLog.isDebugEnabled()) {
saxLog.debug(&quot;endElement(&quot; + namespaceURI + &quot;,&quot; + localName +
&quot;,&quot; + qName + &quot;)&quot;);
}
log.debug(&quot; match=&apos;&quot; + match + &quot;&apos;&quot;);
log.debug(&quot; bodyText=&apos;&quot; + bodyText + &quot;&apos;&quot;);
}
// Parse system properties
bodyText = updateBodyText(bodyText);
// the actual element name is either in localName or qName, depending
// on whether the parser is namespace aware
String name = localName;
if ((name == null) || (name.length() &lt; 1)) {
name = qName;
}
// Fire &quot;body&quot; events for all relevant rules
List&lt;Rule&gt; rules = matches.pop();
if ((rules != null) &amp;&amp; (rules.size() &gt; 0)) {
String bodyText = this.bodyText.toString();
for (int i = 0; i &lt; rules.size(); i++) {
try {
Rule rule = rules.get(i);
if (debug) {
log.debug(&quot; Fire body() for &quot; + rule);
}
rule.body(namespaceURI, name, bodyText);
} catch (Exception e) {
log.error(&quot;Body event threw exception&quot;, e);
throw createSAXException(e);
} catch (Error e) {
log.error(&quot;Body event threw error&quot;, e);
throw e;
}
}
} else {
if (debug) {
log.debug(&quot; No rules found matching &apos;&quot; + match + &quot;&apos;.&quot;);
}
if (rulesValidation) {
log.warn(&quot; No rules found matching &apos;&quot; + match + &quot;&apos;.&quot;);
}
}
// Recover the body text from the surrounding element
bodyText = bodyTexts.pop();
// Fire &quot;end&quot; events for all relevant rules in reverse order
if (rules != null) {
for (int i = 0; i &lt; rules.size(); i++) {
int j = (rules.size() - i) - 1;
try {
Rule rule = rules.get(j);
if (debug) {
log.debug(&quot; Fire end() for &quot; + rule);
}
rule.end(namespaceURI, name);
} catch (Exception e) {
log.error(&quot;End event threw exception&quot;, e);
throw createSAXException(e);
} catch (Error e) {
log.error(&quot;End event threw error&quot;, e);
throw e;
}
}
}
// Recover the previous match expression
int slash = match.lastIndexOf(&apos;/&apos;);
if (slash &gt;= 0) {
match = match.substring(0, slash);
} else {
match = &quot;&quot;;
}
}
</code></pre><p>当我们创建好Digester后,会调用addObjectCreate、addSetProperties、addSetNext方法陆续添加很多Rule,这些方法的实现如代码:</p>
<pre><code> public void addObjectCreate(String pattern, String className,
String attributeName) {
addRule(pattern,
new ObjectCreateRule(className, attributeName));
}
public void addSetProperties(String pattern) {
addRule(pattern,
new SetPropertiesRule());
}
public void addSetNext(String pattern, String methodName,
String paramType) {
addRule(pattern,
new SetNextRule(methodName, paramType));
}
</code></pre><p>这三个方法分别创建ObjectCreateRule、SetPropertiesRule及SetNextRule,为了便于理解,我们举例说明(Server标签):</p>
<pre><code>digester.addObjectCreate(&quot;Server&quot;,&quot;org.apache.catalina.core.StandardServer&quot;,&quot;className&quot;);
digester.addSetProperties(&quot;Server&quot;);
digester.addSetNext(&quot;Server&quot;,&quot;setServer&quot;, &quot;org.apache.catalina.Server&quot;);
</code></pre><p>我们知道最终会创建ObjectCreateRule、SetPropertiesRule及SetNextRule,并且调用addRule方法。</p>
<pre><code> public void addRule(String pattern, Rule rule) {
rule.setDigester(this);
getRules().add(pattern, rule);
}
</code></pre><p>从代码可以看出,addRule方法首先调用getRules方法获取RulesBase,然后调用RulesBase的add方法。代码如下:</p>
<pre><code>//getRules()获取RulesBase
public Rules getRules() {
if (this.rules == null) {
this.rules = new RulesBase();
this.rules.setDigester(this);
}
return (this.rules);
}
//RulesBase的add方法
@Override
public void add(String pattern, Rule rule) {
// to help users who accidently add &apos;/&apos; to the end of their patterns
int patternLength = pattern.length();
if (patternLength&gt;1 &amp;&amp; pattern.endsWith(&quot;/&quot;)) {
pattern = pattern.substring(0, patternLength-1);
}
List&lt;Rule&gt; list = cache.get(pattern);
if (list == null) {
list = new ArrayList&lt;Rule&gt;();
cache.put(pattern, list);
}
list.add(rule);
rules.add(rule);
if (this.digester != null) {
rule.setDigester(this.digester);
}
if (this.namespaceURI != null) {
rule.setNamespaceURI(this.namespaceURI);
}
}
</code></pre><p>其中,cache的数据结构为HashMap<string,list<rule>&gt;,每个键值维护一个List<rule>,由此可知,对Server标签来说,对应的Rule列表为ObjectCreateRule、SetPropertiesRule及SetNextRule。</rule></string,list<rule></p>
<p>Digester解析XML的入口是其parse方法,其处理步骤如下:</p>
<p>1.创建XMLReader ;</p>
<p>2.使用XMLReader解析XML。</p>
<pre><code>public Object parse(InputSource input) throws IOException, SAXException {
configure();
getXMLReader().parse(input);
return (root);
}
//configure()
protected void configure() {
// Do not configure more than once
if (configured) {
return;
}
log = LogFactory.getLog(&quot;org.apache.tomcat.util.digester.Digester&quot;);
saxLog = LogFactory.getLog(&quot;org.apache.tomcat.util.digester.Digester.sax&quot;);
// Perform lazy configuration as needed
initialize(); // call hook method for subclasses that want to be initialized once only
// Nothing else required by default
// Set the configuration flag to avoid repeating
configured = true;
}
</code></pre><p>getXMLReader方法调用getParser创建SAXParser ,然后调用SAXParser 的getXMLReader方法创建XMLReader.</p>
<pre><code>public XMLReader getXMLReader() throws SAXException {
if (reader == null){
reader = getParser().getXMLReader();
}
reader.setDTDHandler(this);
reader.setContentHandler(this);
if (entityResolver == null){
reader.setEntityResolver(this);
} else {
reader.setEntityResolver(entityResolver);
}
reader.setProperty(
&quot;http://xml.org/sax/properties/lexical-handler&quot;, this);
reader.setErrorHandler(this);
return reader;
}
</code></pre><p>getParser方法调用getFactory方法创建SAXParserFactory,然后调用SAXParserFactory的newSAXParser方法创建SAXParser</p>
<pre><code>public SAXParser getParser() {
// Return the parser we already created (if any)
if (parser != null) {
return (parser);
}
// Create a new parser
try {
parser = getFactory().newSAXParser();
} catch (Exception e) {
log.error(&quot;Digester.getParser: &quot;, e);
return (null);
}
return (parser);
}
</code></pre><p>getFactory方法使用SAX的API生成SAXParserFactory实例.</p>
<pre><code>public SAXParserFactory getFactory() throws SAXNotRecognizedException, SAXNotSupportedException,ParserConfigurationException {
if (factory == null) {
factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
// Preserve xmlns attributes
if (namespaceAware) {
factory.setFeature(
&quot;http://xml.org/sax/features/namespace-prefixes&quot;,
true);
}
factory.setValidating(validating);
if (validating) {
// Enable DTD validation
factory.setFeature(
&quot;http://xml.org/sax/features/validation&quot;,
true);
// Enable schema validation
factory.setFeature(
&quot;http://apache.org/xml/features/validation/schema&quot;,
true);
}
}
return (factory);
}
</code></pre><p>XMLReader解析XML时,会生成事件,回调Digester的startDocument方法,解析的第一个元素是Server,此时回调Digester的startElement方法,入参Attributes list即Server上的属性,如port、shutdown等,入参qName即为Server.</p>
<pre><code> @Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes list)
throws SAXException {
boolean debug = log.isDebugEnabled();
if (saxLog.isDebugEnabled()) {
saxLog.debug(&quot;startElement(&quot; + namespaceURI + &quot;,&quot; + localName + &quot;,&quot; +
qName + &quot;)&quot;);
}
// Parse system properties
list = updateAttributes(list);
// Save the body text accumulated for our surrounding element
bodyTexts.push(bodyText);
bodyText = new StringBuilder();
// the actual element name is either in localName or qName, depending
// on whether the parser is namespace aware
String name = localName;
if ((name == null) || (name.length() &lt; 1)) {
name = qName;
}
// Compute the current matching rule
StringBuilder sb = new StringBuilder(match);
if (match.length() &gt; 0) {
sb.append(&apos;/&apos;);
}
sb.append(name);
match = sb.toString();
if (debug) {
log.debug(&quot; New match=&apos;&quot; + match + &quot;&apos;&quot;);
}
// Fire &quot;begin&quot; events for all relevant rules
List&lt;Rule&gt; rules = getRules().match(namespaceURI, match);
matches.push(rules);
if ((rules != null) &amp;&amp; (rules.size() &gt; 0)) {
for (int i = 0; i &lt; rules.size(); i++) {
try {
Rule rule = rules.get(i);
if (debug) {
log.debug(&quot; Fire begin() for &quot; + rule);
}
rule.begin(namespaceURI, name, list);
} catch (Exception e) {
log.error(&quot;Begin event threw exception&quot;, e);
throw createSAXException(e);
} catch (Error e) {
log.error(&quot;Begin event threw error&quot;, e);
throw e;
}
}
} else {
if (debug) {
log.debug(&quot; No rules found matching &apos;&quot; + match + &quot;&apos;.&quot;);
}
}
}
</code></pre><p>startElement方法的处理步骤如下:</p>
<p>1.match刚开始为空字符串,拼接Server后变为Server。</p>
<p>2.调用RulesBase的match方法,返回cache中按照键值Server匹配的ObjectCreateRule、SetPropertiesRule及SetNextRule。</p>
<p>3.循环列表依次遍历ObjectCreateRule、SetPropertiesRule及SetNextRule,并调用它们的begin方法。</p>
<p>ObjectCreateRule的begin方法将生成Server的实例(默认为”org.apache.catalina.core.StandardServer”,用户可以通过给Server标签指定className使用其它Server实现),最后将Server的实例压入Digester的栈中.</p>
<pre><code>@Override
public void begin(String namespace, String name, Attributes attributes)
throws Exception {
// Identify the name of the class to instantiate
String realClassName = className;
if (attributeName != null) {
String value = attributes.getValue(attributeName);
if (value != null) {
realClassName = value;
}
}
if (digester.log.isDebugEnabled()) {
digester.log.debug(&quot;[ObjectCreateRule]{&quot; + digester.match +
&quot;}New &quot; + realClassName);
}
if (realClassName == null) {
throw new NullPointerException(&quot;No class name specified for &quot; +
namespace + &quot; &quot; + name);
}
// Instantiate the new object and push it on the context stack
Class&lt;?&gt; clazz = digester.getClassLoader().loadClass(realClassName);
Object instance = clazz.newInstance();
digester.push(instance);
}
</code></pre><p>SetPropertiesRule的begin方法首先将刚才压入栈中的Server实例出栈,然后给Server实例设置各个属性值,如port、shutdown等:</p>
<pre><code>@Override
public void begin(String namespace, String theName, Attributes attributes)
throws Exception {
// Populate the corresponding properties of the top object
Object top = digester.peek();
if (digester.log.isDebugEnabled()) {
if (top != null) {
digester.log.debug(&quot;[SetPropertiesRule]{&quot; + digester.match +
&quot;} Set &quot; + top.getClass().getName() +
&quot; properties&quot;);
} else {
digester.log.debug(&quot;[SetPropertiesRule]{&quot; + digester.match +
&quot;} Set NULL properties&quot;);
}
}
// set up variables for custom names mappings
int attNamesLength = 0;
if (attributeNames != null) {
attNamesLength = attributeNames.length;
}
int propNamesLength = 0;
if (propertyNames != null) {
propNamesLength = propertyNames.length;
}
for (int i = 0; i &lt; attributes.getLength(); i++) {
String name = attributes.getLocalName(i);
if (&quot;&quot;.equals(name)) {
name = attributes.getQName(i);
}
String value = attributes.getValue(i);
// we&apos;ll now check for custom mappings
for (int n = 0; n&lt;attNamesLength; n++) {
if (name.equals(attributeNames[n])) {
if (n &lt; propNamesLength) {
// set this to value from list
name = propertyNames[n];
} else {
// set name to null
// we&apos;ll check for this later
name = null;
}
break;
}
}
if (digester.log.isDebugEnabled()) {
digester.log.debug(&quot;[SetPropertiesRule]{&quot; + digester.match +
&quot;} Setting property &apos;&quot; + name + &quot;&apos; to &apos;&quot; +
value + &quot;&apos;&quot;);
}
if (!digester.isFakeAttribute(top, name)
&amp;&amp; !IntrospectionUtils.setProperty(top, name, value)
&amp;&amp; digester.getRulesValidation()) {
digester.log.warn(&quot;[SetPropertiesRule]{&quot; + digester.match +
&quot;} Setting property &apos;&quot; + name + &quot;&apos; to &apos;&quot; +
value + &quot;&apos; did not find a matching property.&quot;);
}
}
}
</code></pre><p>SetNextRule的begin不做什么动作。当遇到Server的结束标签时,还会依次调用ObjectCreateRule、SetPropertiesRule及SetNextRule的end方法,不再赘述。所有元素的解析都与Server标签同理,最终将server.xml文件中设置的元素及其属性值,构造出tomcat中的容器,如:Server、Service、Connector等.</p>
]]></content>
<summary type="html">
&lt;h1 id=&quot;1、文件的加载&quot;&gt;&lt;a href=&quot;#1、文件的加载&quot; class=&quot;headerlink&quot; title=&quot;1、文件的加载&quot;&gt;&lt;/a&gt;1、文件的加载&lt;/h1&gt;&lt;p&gt;Bootstrap的load方法是加载Tomcat的server.xml的入口,load方法实际通过反射调用catalinaDaemon(类型为Catalina)的load方法:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/**
* Load daemon.
*/
private void load(String[] arguments)
throws Exception {
// Call the load() method
String methodName = &amp;quot;load&amp;quot;;
Object param[];
Class&amp;lt;?&amp;gt; paramTypes[];
if (arguments==null || arguments.length==0) {
paramTypes = null;
param = null;
} else {
paramTypes = new Class[1];
paramTypes[0] = arguments.getClass();
param = new Object[1];
param[0] = arguments;
}
Method method =
catalinaDaemon.getClass().getMethod(methodName, paramTypes);//通过反射机制调用Catalina类的load方法。
if (log.isDebugEnabled())
log.debug(&amp;quot;Calling startup class &amp;quot; + method);
method.invoke(catalinaDaemon, param);
}
&lt;/code&gt;&lt;/pre&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>Tommcat源码学习(三)--Tomcat_7.0.70停止过程分析</title>
<link href="http://zhengweishan.oschina.io/2017/02/07/%EF%BC%88%E4%B8%89%EF%BC%89Tomcat_7.0.70%E5%81%9C%E6%AD%A2%E5%88%86%E6%9E%90/"/>
<id>http://zhengweishan.oschina.io/2017/02/07/(三)Tomcat_7.0.70停止分析/</id>
<published>2017-02-06T16:00:00.000Z</published>
<updated>2017-03-01T08:50:57.655Z</updated>
<content type="html"><![CDATA[<p>Tomcat关闭命令(Linux下,大部分生产环境都是部署在Linux系统下):</p>
<pre><code>sh shutdown.sh
</code></pre><p>执行这个命令之后,tomcat会为我们做了哪些操作呢?下面就来简单分析下。</p>
<p>shutdown.sh代码清单如下:</p>
<pre><code># Better OS/400 detection: see Bugzilla 31132
os400=false
case &quot;`uname`&quot; in
OS400*) os400=true;;
esac
# resolve links - $0 may be a softlink
PRG=&quot;$0&quot;
while [ -h &quot;$PRG&quot; ] ; do
ls=`ls -ld &quot;$PRG&quot;`
link=`expr &quot;$ls&quot; : &apos;.*-&gt; \(.*\)$&apos;`
if expr &quot;$link&quot; : &apos;/.*&apos; &gt; /dev/null; then
PRG=&quot;$link&quot;
else
PRG=`dirname &quot;$PRG&quot;`/&quot;$link&quot;
fi
done
PRGDIR=`dirname &quot;$PRG&quot;`
EXECUTABLE=catalina.sh
# Check that target executable exists
if $os400; then
# -x will Only work on the os400 if the files are:
# 1. owned by the user
# 2. owned by the PRIMARY group of the user
# this will not work if the user belongs in secondary groups
eval
else
if [ ! -x &quot;$PRGDIR&quot;/&quot;$EXECUTABLE&quot; ]; then
echo &quot;Cannot find $PRGDIR/$EXECUTABLE&quot;
echo &quot;The file is absent or does not have execute permission&quot;
echo &quot;This file is needed to run this program&quot;
exit 1
fi
fi
exec &quot;$PRGDIR&quot;/&quot;$EXECUTABLE&quot; stop &quot;$@&quot;
</code></pre><a id="more"></a>
<p>从上面的代码可以看出来,这里和启动文件是一样的,也有主要的两个变量:</p>
<pre><code>PRGDIR:当前shell脚本所在的路径;
EXECUTABLE:脚本catalina.sh
</code></pre><p>从最后一行代码可以知道,执行catalina.sh,并传递参数:stop</p>
<p>catalina.sh 与之相关的代码清单如下:</p>
<pre><code>elif [ &quot;$1&quot; = &quot;stop&quot; ] ; then
shift
SLEEP=5
if [ ! -z &quot;$1&quot; ]; then
echo $1 | grep &quot;[^0-9]&quot; &gt;/dev/null 2&gt;&amp;1
if [ $? -gt 0 ]; then
SLEEP=$1
shift
fi
fi
FORCE=0
if [ &quot;$1&quot; = &quot;-force&quot; ]; then
shift
FORCE=1
fi
if [ ! -z &quot;$CATALINA_PID&quot; ]; then
if [ -f &quot;$CATALINA_PID&quot; ]; then
if [ -s &quot;$CATALINA_PID&quot; ]; then
kill -0 `cat &quot;$CATALINA_PID&quot;` &gt;/dev/null 2&gt;&amp;1
if [ $? -gt 0 ]; then
echo &quot;PID file found but no matching process was found. Stop aborted.&quot;
exit 1
fi
else
echo &quot;PID file is empty and has been ignored.&quot;
fi
else
echo &quot;\$CATALINA_PID was set but the specified file does not exist. Is Tomcat running? Stop aborted.&quot;
exit 1
fi
fi
eval &quot;\&quot;$_RUNJAVA\&quot;&quot; $LOGGING_MANAGER $JAVA_OPTS \
-Djava.endorsed.dirs=&quot;\&quot;$JAVA_ENDORSED_DIRS\&quot;&quot; -classpath &quot;\&quot;$CLASSPATH\&quot;&quot; \
-Dcatalina.base=&quot;\&quot;$CATALINA_BASE\&quot;&quot; \
-Dcatalina.home=&quot;\&quot;$CATALINA_HOME\&quot;&quot; \
-Djava.io.tmpdir=&quot;\&quot;$CATALINA_TMPDIR\&quot;&quot; \
org.apache.catalina.startup.Bootstrap &quot;$@&quot; stop
</code></pre><p>最终使用java命令执行了org.apache.catalina.startup.Bootstrap类中的main方法,参数是stop。</p>
<pre><code> public static void main(String args[]) {
if (daemon == null) {
// Don&apos;t set daemon until init() has completed
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.init();
} catch (Throwable t) {
handleThrowable(t);
t.printStackTrace();
return;
}
daemon = bootstrap;
} else {
// When running as a service the call to stop will be on a new
// thread so make sure the correct class loader is used to prevent
// a range of class not found exceptions.
Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
}
try {
String command = &quot;start&quot;;
if (args.length &gt; 0) {
command = args[args.length - 1];
}
if (command.equals(&quot;startd&quot;)) {
args[args.length - 1] = &quot;start&quot;;
daemon.load(args);
daemon.start();
} else if (command.equals(&quot;stopd&quot;)) {
args[args.length - 1] = &quot;stop&quot;;
daemon.stop();
} else if (command.equals(&quot;start&quot;)) {
daemon.setAwait(true);
daemon.load(args);
daemon.start();
} else if (command.equals(&quot;stop&quot;)) {
daemon.stopServer(args);
} else if (command.equals(&quot;configtest&quot;)) {
daemon.load(args);
if (null==daemon.getServer()) {
System.exit(1);
}
System.exit(0);
} else {
log.warn(&quot;Bootstrap: command \&quot;&quot; + command + &quot;\&quot; does not exist.&quot;);
}
} catch (Throwable t) {
// Unwrap the Exception for clearer error reporting
if (t instanceof InvocationTargetException &amp;&amp;
t.getCause() != null) {
t = t.getCause();
}
handleThrowable(t);
t.printStackTrace();
System.exit(1);
}
}
</code></pre><p>当传递参数stop的时候,command等于stop,此时main方法的执行步骤如下:</p>
<ul>
<li>初始化Bootstrap(启动的时候已经介绍过就不在介绍)</li>
<li><p>停止服务</p>
<p> 通过调用Bootstrap的stopServer方法停止Tomcat,其实质是用反射调用catalinaDaemon(类型是Catalina)的stopServer方法。</p>
<pre><code>/**
* Stop the standalone server.
*/
public void stopServer(String[] arguments)
throws Exception {
Object param[];
Class&lt;?&gt; paramTypes[];
if (arguments==null || arguments.length==0) {
paramTypes = null;
param = null;
} else {
paramTypes = new Class[1];
paramTypes[0] = arguments.getClass();
param = new Object[1];
param[0] = arguments;
}
Method method =
catalinaDaemon.getClass().getMethod(&quot;stopServer&quot;, paramTypes);//反射调用catalinaDaemon(类型是Catalina)的stopServer方法
method.invoke(catalinaDaemon, param);
}
</code></pre><p> Catalina的stopServer方法的执行步骤如下:</p>
<p> 代码清单:</p>
<pre><code>public void stopServer() {
stopServer(null);
}
public void stopServer(String[] arguments) {
if (arguments != null) {
arguments(arguments);
}
Server s = getServer();
if( s == null ) {//服务不存在
// Create and execute our Digester
Digester digester = createStopDigester();//Digester解析server.xml文件,以构造出Server容器
File file = configFile();
FileInputStream fis = null;
try {
InputSource is =
new InputSource(file.toURI().toURL().toString());
fis = new FileInputStream(file);
is.setByteStream(fis);
digester.push(this);
digester.parse(is);
} catch (Exception e) {
log.error(&quot;Catalina.stop: &quot;, e);
System.exit(1);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore
}
}
}
} else {
// Server object already present. Must be running as a service
try {
s.stop();
} catch (LifecycleException e) {
log.error(&quot;Catalina.stop: &quot;, e);
}
return;
}
// Stop the existing server
s = getServer();
if (s.getPort()&gt;0) {
Socket socket = null;
OutputStream stream = null;
try {
socket = new Socket(s.getAddress(), s.getPort());//创建Socket对象连接启动Tomcat时创建的ServerSocket
stream = socket.getOutputStream();
String shutdown = s.getShutdown();
for (int i = 0; i &lt; shutdown.length(); i++) {
stream.write(shutdown.charAt(i));//发送shutdown命令
}
stream.flush();
} catch (ConnectException ce) {
log.error(sm.getString(&quot;catalina.stopServer.connectException&quot;,
s.getAddress(),
String.valueOf(s.getPort())));
log.error(&quot;Catalina.stop: &quot;, ce);
System.exit(1);
} catch (IOException e) {
log.error(&quot;Catalina.stop: &quot;, e);
System.exit(1);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
}
} else {
log.error(sm.getString(&quot;catalina.stopServer&quot;));
System.exit(1);
}
}
</code></pre></li>
</ul>
<pre><code>- 创建Digester解析server.xml文件(此处只解析标签),以构造出Server容器(此时Server容器的子容器没有被实例化);
- 从实例化的Server容器获取Server的socket监听端口和地址,然后创建Socket对象连接启动Tomcat时创建的ServerSocket,最后向ServerSocket发送SHUTDOWN命令。根据
@Override
public void await() {
// Negative values - don&apos;t wait on port - tomcat is embedded or we just don&apos;t like ports
if( port == -2 ) {
// undocumented yet - for embedding apps that are around, alive.
return;
}
if( port==-1 ) {
try {
awaitThread = Thread.currentThread();
while(!stopAwait) {
try {
Thread.sleep( 10000 );
} catch( InterruptedException ex ) {
// continue and check the flag
}
}
} finally {
awaitThread = null;
}
return;
}
// Set up a server socket to wait on
try {
awaitSocket = new ServerSocket(port, 1,
InetAddress.getByName(address));//创建socket连接的服务端对象ServerSocket
} catch (IOException e) {
log.error(&quot;StandardServer.await: create[&quot; + address
+ &quot;:&quot; + port
+ &quot;]: &quot;, e);
return;
}
try {
awaitThread = Thread.currentThread();
// Loop waiting for a connection and a valid command
while (!stopAwait) {
ServerSocket serverSocket = awaitSocket;
if (serverSocket == null) {
break;
}
// Wait for the next connection
Socket socket = null;
StringBuilder command = new StringBuilder();//创建一个对象循环接收socket中的字符
try {
InputStream stream;
long acceptStartTime = System.currentTimeMillis();
try {
socket = serverSocket.accept();
socket.setSoTimeout(10 * 1000); // Ten seconds
stream = socket.getInputStream();
} catch (SocketTimeoutException ste) {
// This should never happen but bug 56684 suggests that
// it does.
log.warn(sm.getString(&quot;standardServer.accept.timeout&quot;,
Long.valueOf(System.currentTimeMillis() - acceptStartTime)), ste);
continue;
} catch (AccessControlException ace) {
log.warn(&quot;StandardServer.accept security exception: &quot;
+ ace.getMessage(), ace);
continue;
} catch (IOException e) {
if (stopAwait) {
// Wait was aborted with socket.close()
break;
}
log.error(&quot;StandardServer.await: accept: &quot;, e);
break;
}
// Read a set of characters from the socket
int expected = 1024; // Cut off to avoid DoS attack
while (expected &lt; shutdown.length()) {
if (random == null)
random = new Random();
expected += (random.nextInt() % 1024);
}
while (expected &gt; 0) {
int ch = -1;
try {
ch = stream.read();
} catch (IOException e) {
log.warn(&quot;StandardServer.await: read: &quot;, e);
ch = -1;
}
if (ch &lt; 32) // Control character or EOF terminates loop
break;
command.append((char) ch);
expected--;
}
} finally {
// Close the socket now that we are done with it
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
// Match against our command string
boolean match = command.toString().equals(shutdown);
if (match) { //如果接收到的命令与SHUTDOWN匹配(由于使用了equals,所以shutdown命令必须是大写的),那么退出循环等待
log.info(sm.getString(&quot;standardServer.shutdownViaPort&quot;));
break;
} else
log.warn(&quot;StandardServer.await: Invalid command &apos;&quot;
+ command.toString() + &quot;&apos; received&quot;);
}
} finally {
ServerSocket serverSocket = awaitSocket;
awaitThread = null;
awaitSocket = null;
// Close the server socket and return
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// Ignore
}
}
}
}
内容,ServerSocket循环等待接收到SHUTDOWN命令后,最终调用stop方法停止Tomcat。
最后,我们看看Catalina的stop方法的实现,其执行步骤如下:
1. 将启动过程中添加的关闭钩子移除。Tomcat启动过程辛辛苦苦添加的关闭钩子为什么又要去掉呢?因为关闭钩子是为了在JVM异常退出后,进行资源的回收工作。主动停止Tomcat时调用的stop方法里已经包含了资源回收的内容,所以不再需要这个钩子了。
2. 停止Server容器。有关容器的停止内容,请阅读后续文章。
3. 代码清单:
/**
* Stop an existing server instance.****
*/
public void stop() {
try {
// Remove the ShutdownHook first so that server.stop()
// doesn&apos;t get invoked twice
if (useShutdownHook) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);//将启动过程中添加的关闭钩子移除
// If JULI is being used, re-enable JULI&apos;s shutdown to ensure
// log messages are not lost
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).setUseShutdownHook(
true);
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This will fail on JDK 1.2. Ignoring, as Tomcat can run
// fine without the shutdown hook.
}
// Shut down the server
try {
Server s = getServer();
LifecycleState state = s.getState();
if (LifecycleState.STOPPING_PREP.compareTo(state) &lt;= 0
&amp;&amp; LifecycleState.DESTROYED.compareTo(state) &gt;= 0) {
// Nothing to do. stop() was already called
} else {
s.stop();//停止Server容器。
s.destroy();
}
} catch (LifecycleException e) {
log.error(&quot;Catalina.stop&quot;, e);
}
}
总结:
通过对Tomcat源码的分析我们了解到Tomcat的启动和停止都离不开org.apache.catalina.startup.Bootstrap。
当停止Tomcat时,已经启动的Tomcat作为socket服务端,停止脚本启动的Bootstrap进程作为socket客户端向服务端发送shutdown命令
,两个进程通过共享server.xml里Server标签的端口以及地址信息打通了socket的通信。
</code></pre>]]></content>
<summary type="html">
&lt;p&gt;Tomcat关闭命令(Linux下,大部分生产环境都是部署在Linux系统下):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;sh shutdown.sh
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;执行这个命令之后,tomcat会为我们做了哪些操作呢?下面就来简单分析下。&lt;/p&gt;
&lt;p&gt;shutdown.sh代码清单如下:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Better OS/400 detection: see Bugzilla 31132
os400=false
case &amp;quot;`uname`&amp;quot; in
OS400*) os400=true;;
esac
# resolve links - $0 may be a softlink
PRG=&amp;quot;$0&amp;quot;
while [ -h &amp;quot;$PRG&amp;quot; ] ; do
ls=`ls -ld &amp;quot;$PRG&amp;quot;`
link=`expr &amp;quot;$ls&amp;quot; : &amp;apos;.*-&amp;gt; \(.*\)$&amp;apos;`
if expr &amp;quot;$link&amp;quot; : &amp;apos;/.*&amp;apos; &amp;gt; /dev/null; then
PRG=&amp;quot;$link&amp;quot;
else
PRG=`dirname &amp;quot;$PRG&amp;quot;`/&amp;quot;$link&amp;quot;
fi
done
PRGDIR=`dirname &amp;quot;$PRG&amp;quot;`
EXECUTABLE=catalina.sh
# Check that target executable exists
if $os400; then
# -x will Only work on the os400 if the files are:
# 1. owned by the user
# 2. owned by the PRIMARY group of the user
# this will not work if the user belongs in secondary groups
eval
else
if [ ! -x &amp;quot;$PRGDIR&amp;quot;/&amp;quot;$EXECUTABLE&amp;quot; ]; then
echo &amp;quot;Cannot find $PRGDIR/$EXECUTABLE&amp;quot;
echo &amp;quot;The file is absent or does not have execute permission&amp;quot;
echo &amp;quot;This file is needed to run this program&amp;quot;
exit 1
fi
fi
exec &amp;quot;$PRGDIR&amp;quot;/&amp;quot;$EXECUTABLE&amp;quot; stop &amp;quot;$@&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>Tomcat源码学习(二)--Tomcat_7.0.70 启动分析</title>
<link href="http://zhengweishan.oschina.io/2017/02/06/%EF%BC%88%E4%BA%8C%EF%BC%89Tomcat_7.0.70%E5%90%AF%E5%8A%A8%E5%88%86%E6%9E%90/"/>
<id>http://zhengweishan.oschina.io/2017/02/06/(二)Tomcat_7.0.70启动分析/</id>
<published>2017-02-05T16:00:00.000Z</published>
<updated>2017-03-01T08:50:27.024Z</updated>
<content type="html"><![CDATA[<h2 id="1、运行Tomcat-7-0-70源码"><a href="#1、运行Tomcat-7-0-70源码" class="headerlink" title="1、运行Tomcat_7.0.70源码"></a>1、运行Tomcat_7.0.70源码</h2><p>项目build成功后,刷新整个项目,会发现多出一个output目录:</p>
<p><img src="http://i.imgur.com/lEmnktv.png" alt=""></p>
<p>为了让应用跑起来,可以检查一下output\build\conf下是否已经有配置文件,这些文件实际是从项目根路径conf目录下拷贝过来的。</p>
<p><img src="http://i.imgur.com/7riC9qx.png" alt=""></p>
<p>找到BootStarp.java文件,Debug前加入默认的catalina home路径作为启动参数。</p>
<p><img src="http://i.imgur.com/vOat4iI.png" alt=""></p>
<p>路径设置为output下build的绝对路径。比如我自己的机器设置的值是-Dcatalina.home=”W:\workspace\tc7.0.70\output\build”</p>
<p><img src="http://i.imgur.com/ac9aXEQ.png" alt=""><br>这样就可以愉快的在文件中加入断点Debug源码分析了。运行之后的效果图:<br><img src="http://i.imgur.com/KxbTJD8.png" alt=""><br><img src="http://i.imgur.com/XlnUToa.png" alt=""><br>OK,源码到此运行成功,完美~</p>
<a id="more"></a>
<h2 id="2、启动分析"><a href="#2、启动分析" class="headerlink" title="2、启动分析"></a>2、启动分析</h2><p>上面运行源码用的BootStarp.java这个类中的main方法(后面再对这个main方法做分析),实际上我们在用Tomcat的时候,大部分都是使用脚本文件startup.sh、startup.bat、shutdown.sh、shutdown.bat等脚本或者批处理命令来启动Tomcat的.大家一定知道改如何使用它,但是它们究竟是如何实现的,下面就一点一点的分析。</p>
<p>由于在生产环境中,Tomcat一般部署在Linux系统下,所以将以startup.sh和shutdown.sh等shell脚本为准,对Tomcat的启动与停止进行分析。</p>
<p>Linux下启动Tomcat的命令:</p>
<pre><code>sh startup.sh
</code></pre><p>下面将从shell脚本startup.sh开始分析Tomcat的启动过程。</p>
<p>startup.sh脚本代码清单:</p>
<pre><code># Better OS/400 detection: see Bugzilla 31132
os400=false
case &quot;`uname`&quot; in
OS400*) os400=true;;
esac
# resolve links - $0 may be a softlink
PRG=&quot;$0&quot;
while [ -h &quot;$PRG&quot; ] ; do
ls=`ls -ld &quot;$PRG&quot;`
link=`expr &quot;$ls&quot; : &apos;.*-&gt; \(.*\)$&apos;`
if expr &quot;$link&quot; : &apos;/.*&apos; &gt; /dev/null; then
PRG=&quot;$link&quot;
else
PRG=`dirname &quot;$PRG&quot;`/&quot;$link&quot;
fi
done
PRGDIR=`dirname &quot;$PRG&quot;`
EXECUTABLE=catalina.sh
# Check that target executable exists
if $os400; then
# -x will Only work on the os400 if the files are:
# 1. owned by the user
# 2. owned by the PRIMARY group of the user
# this will not work if the user belongs in secondary groups
eval
else
if [ ! -x &quot;$PRGDIR&quot;/&quot;$EXECUTABLE&quot; ]; then
echo &quot;Cannot find $PRGDIR/$EXECUTABLE&quot;
echo &quot;The file is absent or does not have execute permission&quot;
echo &quot;This file is needed to run this program&quot;
exit 1
fi
fi
exec &quot;$PRGDIR&quot;/&quot;$EXECUTABLE&quot; start &quot;$@&quot;
</code></pre><p>从代码清单可以看出有两个主要的变量,分别是:</p>
<pre><code>1. PRGDIR:当前shell脚本所在的路径;
2. EXECUTABLE:脚本catalina.sh。
</code></pre><p><code>exec &quot;$PRGDIR&quot;/&quot;$EXECUTABLE&quot; start &quot;$@&quot;</code> 我们知道执行了shell脚本catalina.sh,并且传递参数start。</p>
<p>catalina.sh 脚本代码(部分)清单:</p>
<pre><code> shift
touch &quot;$CATALINA_OUT&quot;
if [ &quot;$1&quot; = &quot;-security&quot; ] ; then
if [ $have_tty -eq 1 ]; then
echo &quot;Using Security Manager&quot;
fi
shift
eval $_NOHUP &quot;\&quot;$_RUNJAVA\&quot;&quot; &quot;\&quot;$LOGGING_CONFIG\&quot;&quot; $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs=&quot;\&quot;$JAVA_ENDORSED_DIRS\&quot;&quot; -classpath &quot;\&quot;$CLASSPATH\&quot;&quot; \
-Djava.security.manager \
-Djava.security.policy==&quot;\&quot;$CATALINA_BASE/conf/catalina.policy\&quot;&quot; \
-Dcatalina.base=&quot;\&quot;$CATALINA_BASE\&quot;&quot; \
-Dcatalina.home=&quot;\&quot;$CATALINA_HOME\&quot;&quot; \
-Djava.io.tmpdir=&quot;\&quot;$CATALINA_TMPDIR\&quot;&quot; \
org.apache.catalina.startup.Bootstrap &quot;$@&quot; start \
&gt;&gt; &quot;$CATALINA_OUT&quot; 2&gt;&amp;1 &quot;&amp;&quot;
else
eval $_NOHUP &quot;\&quot;$_RUNJAVA\&quot;&quot; &quot;\&quot;$LOGGING_CONFIG\&quot;&quot; $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs=&quot;\&quot;$JAVA_ENDORSED_DIRS\&quot;&quot; -classpath &quot;\&quot;$CLASSPATH\&quot;&quot; \
-Dcatalina.base=&quot;\&quot;$CATALINA_BASE\&quot;&quot; \
-Dcatalina.home=&quot;\&quot;$CATALINA_HOME\&quot;&quot; \
-Djava.io.tmpdir=&quot;\&quot;$CATALINA_TMPDIR\&quot;&quot; \
org.apache.catalina.startup.Bootstrap &quot;$@&quot; start \
&gt;&gt; &quot;$CATALINA_OUT&quot; 2&gt;&amp;1 &quot;&amp;&quot;
fi
if [ ! -z &quot;$CATALINA_PID&quot; ]; then
echo $! &gt; &quot;$CATALINA_PID&quot;
fi
echo &quot;Tomcat started.&quot;
</code></pre><p>从上面可以看出,脚本最终使用java命令执行了org.apache.catalina.startup.Bootstrap类中的main方法,参数也是start。Bootstrap的main方法的实现如下:</p>
<pre><code>public static void main(String args[]) {
if (daemon == null) {
// Don&apos;t set daemon until init() has completed
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.init();
} catch (Throwable t) {
handleThrowable(t);
t.printStackTrace();
return;
}
daemon = bootstrap;
} else {
// When running as a service the call to stop will be on a new
// thread so make sure the correct class loader is used to prevent
// a range of class not found exceptions.
Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
}
try {
String command = &quot;start&quot;;
if (args.length &gt; 0) {
command = args[args.length - 1];
}
if (command.equals(&quot;startd&quot;)) {
args[args.length - 1] = &quot;start&quot;;
daemon.load(args);
daemon.start();
} else if (command.equals(&quot;stopd&quot;)) {
args[args.length - 1] = &quot;stop&quot;;
daemon.stop();
} else if (command.equals(&quot;start&quot;)) {
//传递参数为start
daemon.setAwait(true);
daemon.load(args);
daemon.start();
} else if (command.equals(&quot;stop&quot;)) {
daemon.stopServer(args);
} else if (command.equals(&quot;configtest&quot;)) {
daemon.load(args);
if (null==daemon.getServer()) {
System.exit(1);
}
System.exit(0);
} else {
log.warn(&quot;Bootstrap: command \&quot;&quot; + command + &quot;\&quot; does not exist.&quot;);
}
} catch (Throwable t) {
// Unwrap the Exception for clearer error reporting
if (t instanceof InvocationTargetException &amp;&amp;
t.getCause() != null) {
t = t.getCause();
}
handleThrowable(t);
t.printStackTrace();
System.exit(1);
}
}
</code></pre><p>当传递参数start的时候,command等于start,此时main方法的执行步骤如下:</p>
<ul>
<li>初始化Bootstrap</li>
</ul>
<pre><code>public void init() throws Exception{
// Set Catalina path
setCatalinaHome(); //1.设置Catalina路径,默认为Tomcat的根目录
setCatalinaBase();
initClassLoaders();//2.初始化Tomcat的类加载器
Thread.currentThread().setContextClassLoader(catalinaLoader);//3.并设置线程上下文类加载器
SecurityClassLoad.securityClassLoad(catalinaLoader);
// Load our startup class and call its process() method
if (log.isDebugEnabled())
log.debug(&quot;Loading startup class&quot;);
//4.用反射实例化org.apache.catalina.startup.Catalina对象,并且使用反射调用其setParentClassLoader方法,给Catalina对象设置Tomcat类加载体系的顶级加载器(Java自带的三种类加载器除外)
Class&lt;?&gt; startupClass =
catalinaLoader.loadClass
(&quot;org.apache.catalina.startup.Catalina&quot;);
Object startupInstance = startupClass.newInstance();
// Set the shared extensions class loader
if (log.isDebugEnabled())
log.debug(&quot;Setting startup class properties&quot;);
String methodName = &quot;setParentClassLoader&quot;;
Class&lt;?&gt; paramTypes[] = new Class[1];
paramTypes[0] = Class.forName(&quot;java.lang.ClassLoader&quot;);
Object paramValues[] = new Object[1];
paramValues[0] = sharedLoader;
Method method =
startupInstance.getClass().getMethod(methodName, paramTypes);
method.invoke(startupInstance, paramValues);
catalinaDaemon = startupInstance;
}
</code></pre><ul>
<li><p>加载、解析server.xml配置文件</p>
<p> 当传递参数start的时候,会调用Bootstrap的load方法:</p>
<pre><code> /**
* Load daemon.
*/
private void load(String[] arguments)
throws Exception {
// Call the load() method
String methodName = &quot;load&quot;;
Object param[];
Class&lt;?&gt; paramTypes[];
if (arguments==null || arguments.length==0) {
paramTypes = null;
param = null;
} else {
paramTypes = new Class[1];
paramTypes[0] = arguments.getClass();
param = new Object[1];
param[0] = arguments;
}
Method method =
catalinaDaemon.getClass().getMethod(methodName, paramTypes);//用反射调用catalinaDaemon(类型是Catalina)的load方法加载和解析server.xml配置文件。
if (log.isDebugEnabled())
log.debug(&quot;Calling startup class &quot; + method);
method.invoke(catalinaDaemon, param);
}
</code></pre><p>备注:如何加载和解析server.xml配置文件,后面会博客会陆续给出。</p>
</li>
<li><p>启动Tomcat</p>
<p> 当传递参数start的时候,调用Bootstrap的load方法之后会接着调用start方法:</p>
<pre><code>/**
* Start the Catalina daemon.
*/
public void start()
throws Exception {
if( catalinaDaemon==null ) init();
Method method = catalinaDaemon.getClass().getMethod(&quot;start&quot;, (Class [] )null);//启动Tomcat,此方法实际是用反射调用了catalinaDaemon(类型是Catalina)的start方法
method.invoke(catalinaDaemon, (Object [])null);
}
</code></pre><p>Catalina的start方法如下:</p>
<pre><code> /**
* Start a new server instance.
*/
public void start() {
//1.验证Server容器是否已经实例化
if (getServer() == null) {
load(); //如果没有实例化Server容器,还会再次调用Catalina的load方法加载和解析server.xml,这也说明Tomcat只允许Server容器通过配置在server.xml的方式生成,用户也可以自己实现Server接口创建自定义的Server容器以取代默认的StandardServer。
}
if (getServer() == null) {
log.fatal(&quot;Cannot start server. Server instance is not configured.&quot;);
return;
}
long t1 = System.nanoTime();
// Start the new server
try {
getServer().start(); //2.启动Server容器
} catch (LifecycleException e) {
log.fatal(sm.getString(&quot;catalina.serverStartFail&quot;), e);
try {
getServer().destroy();
} catch (LifecycleException e1) {
log.debug(&quot;destroy() failed for failed Server &quot;, e1);
}
return;
}
long t2 = System.nanoTime();
if(log.isInfoEnabled()) {
log.info(&quot;Server startup in &quot; + ((t2 - t1) / 1000000) + &quot; ms&quot;);
}
// Register shutdown hook
if (useShutdownHook) {
if (shutdownHook == null) {
shutdownHook = new CatalinaShutdownHook();//3.设置关闭钩子
}
Runtime.getRuntime().addShutdownHook(shutdownHook);
// If JULI is being used, disable JULI&apos;s shutdown hook since
// shutdown hooks run in parallel and log messages may be lost
// if JULI&apos;s hook completes before the CatalinaShutdownHook()
LogManager logManager = LogManager.getLogManager();
if (logManager instanceof ClassLoaderLogManager) {
((ClassLoaderLogManager) logManager).setUseShutdownHook(
false);
}
}
if (await) {
await();//4.最后调用Catalina的await方法循环等待接收Tomcat的shutdown命令
stop();//5.如果Tomcat运行正常且没有收到shutdown命令,是不会向下执行此方法的,当接收到shutdown命令,Catalina的await方法会退出循环等待,然后顺序执行stop方法停止Tomcat
}
}
</code></pre><p>Catalina的await方法实际只是代理执行了Server容器的await方法。</p>
<pre><code>/**
* Await and shutdown.
*/
public void await() {
getServer().await();
}
</code></pre><p>以Server的默认实现StandardServer为例,其await方法如下:</p>
<pre><code>@Override
public void await() {
// Negative values - don&apos;t wait on port - tomcat is embedded or we just don&apos;t like ports
if( port == -2 ) {
// undocumented yet - for embedding apps that are around, alive.
return;
}
if( port==-1 ) {
try {
awaitThread = Thread.currentThread();
while(!stopAwait) {
try {
Thread.sleep( 10000 );
} catch( InterruptedException ex ) {
// continue and check the flag
}
}
} finally {
awaitThread = null;
}
return;
}
// Set up a server socket to wait on
try {
awaitSocket = new ServerSocket(port, 1,
InetAddress.getByName(address));//创建socket连接的服务端对象ServerSocket
} catch (IOException e) {
log.error(&quot;StandardServer.await: create[&quot; + address
+ &quot;:&quot; + port
+ &quot;]: &quot;, e);
return;
}
try {
awaitThread = Thread.currentThread();
// Loop waiting for a connection and a valid command
while (!stopAwait) {
ServerSocket serverSocket = awaitSocket;
if (serverSocket == null) {
break;
}
// Wait for the next connection
Socket socket = null;
StringBuilder command = new StringBuilder();//创建一个对象循环接收socket中的字符
try {
InputStream stream;
long acceptStartTime = System.currentTimeMillis();
try {
socket = serverSocket.accept();
socket.setSoTimeout(10 * 1000); // Ten seconds
stream = socket.getInputStream();
} catch (SocketTimeoutException ste) {
// This should never happen but bug 56684 suggests that
// it does.
log.warn(sm.getString(&quot;standardServer.accept.timeout&quot;,
Long.valueOf(System.currentTimeMillis() - acceptStartTime)), ste);
continue;
} catch (AccessControlException ace) {
log.warn(&quot;StandardServer.accept security exception: &quot;
+ ace.getMessage(), ace);
continue;
} catch (IOException e) {
if (stopAwait) {
// Wait was aborted with socket.close()
break;
}
log.error(&quot;StandardServer.await: accept: &quot;, e);
break;
}
// Read a set of characters from the socket
int expected = 1024; // Cut off to avoid DoS attack
while (expected &lt; shutdown.length()) {
if (random == null)
random = new Random();
expected += (random.nextInt() % 1024);
}
while (expected &gt; 0) {
int ch = -1;
try {
ch = stream.read();
} catch (IOException e) {
log.warn(&quot;StandardServer.await: read: &quot;, e);
ch = -1;
}
if (ch &lt; 32) // Control character or EOF terminates loop
break;
command.append((char) ch);
expected--;
}
} finally {
// Close the socket now that we are done with it
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
// Match against our command string
boolean match = command.toString().equals(shutdown);
if (match) { //如果接收到的命令与SHUTDOWN匹配(由于使用了equals,所以shutdown命令必须是大写的),那么退出循环等待
log.info(sm.getString(&quot;standardServer.shutdownViaPort&quot;));
break;
} else
log.warn(&quot;StandardServer.await: Invalid command &apos;&quot;
+ command.toString() + &quot;&apos; received&quot;);
}
} finally {
ServerSocket serverSocket = awaitSocket;
awaitThread = null;
awaitSocket = null;
// Close the server socket and return
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// Ignore
}
}
}
}
</code></pre><p>至此,Tomcat启动完毕。</p>
</li>
</ul>
<p>备注:如何启动server,这里不做过多解释,后面会有专门的博客介绍《容器启动过程分析》。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、运行Tomcat-7-0-70源码&quot;&gt;&lt;a href=&quot;#1、运行Tomcat-7-0-70源码&quot; class=&quot;headerlink&quot; title=&quot;1、运行Tomcat_7.0.70源码&quot;&gt;&lt;/a&gt;1、运行Tomcat_7.0.70源码&lt;/h2&gt;&lt;p&gt;项目build成功后,刷新整个项目,会发现多出一个output目录:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/lEmnktv.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;为了让应用跑起来,可以检查一下output\build\conf下是否已经有配置文件,这些文件实际是从项目根路径conf目录下拷贝过来的。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/7riC9qx.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;找到BootStarp.java文件,Debug前加入默认的catalina home路径作为启动参数。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/vOat4iI.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;路径设置为output下build的绝对路径。比如我自己的机器设置的值是-Dcatalina.home=”W:\workspace\tc7.0.70\output\build”&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/ac9aXEQ.png&quot; alt=&quot;&quot;&gt;&lt;br&gt;这样就可以愉快的在文件中加入断点Debug源码分析了。运行之后的效果图:&lt;br&gt;&lt;img src=&quot;http://i.imgur.com/KxbTJD8.png&quot; alt=&quot;&quot;&gt;&lt;br&gt;&lt;img src=&quot;http://i.imgur.com/XlnUToa.png&quot; alt=&quot;&quot;&gt;&lt;br&gt;OK,源码到此运行成功,完美~&lt;/p&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>Tomcat 源码学习(一)--Tomcat_7.0.70 源码运行环境搭建</title>
<link href="http://zhengweishan.oschina.io/2017/02/05/%EF%BC%88%E4%B8%80%EF%BC%89Tomcat7.0.70%E6%BA%90%E4%BB%A3%E7%A0%81%E8%BF%90%E8%A1%8C%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/"/>
<id>http://zhengweishan.oschina.io/2017/02/05/(一)Tomcat7.0.70源代码运行环境搭建/</id>
<published>2017-02-04T16:00:00.000Z</published>
<updated>2017-03-01T08:48:29.343Z</updated>
<content type="html"><![CDATA[<h1 id="1、源码下载"><a href="#1、源码下载" class="headerlink" title="1、源码下载"></a>1、源码下载</h1><p><a href="http://apache.fayea.com/tomcat/tomcat-7/v7.0.70/src/apache-tomcat-7.0.70-src.zip" target="_blank" rel="external">下载地址</a></p>
<h1 id="2、环境配置"><a href="#2、环境配置" class="headerlink" title="2、环境配置"></a>2、环境配置</h1><h2 id="2-1-新建eclipse项目"><a href="#2-1-新建eclipse项目" class="headerlink" title="2.1 新建eclipse项目"></a>2.1 新建eclipse项目</h2><pre><code>新建项目tc7.0.70,其他设置默认就好。
</code></pre><p><img src="http://i.imgur.com/MB1PvoU.png" alt=""></p>
<pre><code>项目建立好之后修改此项目的编译环境,
请选择编译环境为1.6,选择1.7会报错(tomcat-dbcp.jar依赖的是jdk1.6,
选择1.7在建立的时候会报错,这个大家可以尝试下看看是不是),下图就是选择编译环境为1.7的时候报的错误。
</code></pre><p><img src="http://i.imgur.com/NxcOK1m.png" alt=""></p>
<pre><code>修改编译环境:选中项目右键-&gt;Properties-&gt;Java Complier 如下图:
</code></pre><p><img src="http://i.imgur.com/OWOEZBE.png" alt=""></p>
<a id="more"></a>
<h2 id="2-2-导入源码"><a href="#2-2-导入源码" class="headerlink" title="2.2 导入源码"></a>2.2 导入源码</h2><pre><code>将下载的tomcat源码包解压开:
</code></pre><p><img src="http://i.imgur.com/7Dqz8Ry.png" alt=""></p>
<pre><code>修改bin目录为script(为什么要这样做?因为新建的Java项目中默认编译后的文件
存放目录是bin,这样做防止编译后的文件覆盖原来拷贝过去的内容。)
</code></pre><p><img src="http://i.imgur.com/9kHqG1Q.png" alt=""></p>
<pre><code>修改之后拷贝到Eclipse里新建的项目根目录下:
</code></pre><p><img src="http://i.imgur.com/p0itBCq.png" alt=""></p>
<pre><code>将项目中默认的src目录删掉,java和test作为源目录。如图这样操作选中java和test目录:
</code></pre><p><img src="http://i.imgur.com/HuvMgE0.png" alt=""></p>
<pre><code>转换之后如图:(这里有红叉,不要管它,后面就解决这个问题)
</code></pre><p><img src="http://i.imgur.com/rQHdiwu.png" alt=""></p>
<h2 id="2-3-添加需要的jar"><a href="#2-3-添加需要的jar" class="headerlink" title="2.3 添加需要的jar"></a>2.3 添加需要的jar</h2><pre><code>上面说到转换之后有红叉,很明显是缺少一些jar,这就需要我们自己手动添加了,所以我新建了一个depend的文件:
</code></pre><p><img src="http://i.imgur.com/DlWT9WE.png" alt=""></p>
<pre><code>缺少的这些jar包,我整理下统一放在云盘了,大家从下面的地址下载就可以了,不用再来回找了。
</code></pre><p><a href="http://pan.baidu.com/s/1eSjrr1o" target="_blank" rel="external">缺少的jar下载</a>,大家下载之后直接解压,然后放在depend下:<br><img src="http://i.imgur.com/FQ5eorf.png" alt=""></p>
<pre><code>把这些jar包加入到编译路径里,如图:
</code></pre><p><img src="http://i.imgur.com/bcaGd4p.png" alt=""></p>
<pre><code>此时发现test目录下还有错误,实际上是因为test里面用到了junit的一些注解,所以需要将junit4引进来
选中项目右键-&gt;Properties-&gt;Java Build Path如下图:
</code></pre><p><img src="http://i.imgur.com/Egwm8ZO.png" alt=""><br><img src="http://i.imgur.com/SXTAHII.png" alt=""></p>
<pre><code>自此整个项目应该可以编译了。
</code></pre><h2 id="2-4-build(验证能否构建成功)"><a href="#2-4-build(验证能否构建成功)" class="headerlink" title="2.4 build(验证能否构建成功)"></a>2.4 build(验证能否构建成功)</h2><pre><code>运行项目根目录下的build.xml,执行默认的ant任务,看看项目构建的有没有问题。
控制台输出&quot;BUILD SUCCESSFUL&quot;表示编译构建成功。如图:
</code></pre><p><img src="http://i.imgur.com/JExmB3J.png" alt=""><br><img src="http://i.imgur.com/6Qgs4TP.png" alt=""></p>
<pre><code>至此源码运行环境搭建完毕。
</code></pre>]]></content>
<summary type="html">
&lt;h1 id=&quot;1、源码下载&quot;&gt;&lt;a href=&quot;#1、源码下载&quot; class=&quot;headerlink&quot; title=&quot;1、源码下载&quot;&gt;&lt;/a&gt;1、源码下载&lt;/h1&gt;&lt;p&gt;&lt;a href=&quot;http://apache.fayea.com/tomcat/tomcat-7/v7.0.70/src/apache-tomcat-7.0.70-src.zip&quot;&gt;下载地址&lt;/a&gt;&lt;/p&gt;
&lt;h1 id=&quot;2、环境配置&quot;&gt;&lt;a href=&quot;#2、环境配置&quot; class=&quot;headerlink&quot; title=&quot;2、环境配置&quot;&gt;&lt;/a&gt;2、环境配置&lt;/h1&gt;&lt;h2 id=&quot;2-1-新建eclipse项目&quot;&gt;&lt;a href=&quot;#2-1-新建eclipse项目&quot; class=&quot;headerlink&quot; title=&quot;2.1 新建eclipse项目&quot;&gt;&lt;/a&gt;2.1 新建eclipse项目&lt;/h2&gt;&lt;pre&gt;&lt;code&gt;新建项目tc7.0.70,其他设置默认就好。
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/MB1PvoU.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;项目建立好之后修改此项目的编译环境,
请选择编译环境为1.6,选择1.7会报错(tomcat-dbcp.jar依赖的是jdk1.6,
选择1.7在建立的时候会报错,这个大家可以尝试下看看是不是),下图就是选择编译环境为1.7的时候报的错误。
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/NxcOK1m.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;修改编译环境:选中项目右键-&amp;gt;Properties-&amp;gt;Java Complier 如下图:
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/OWOEZBE.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</summary>
<category term="Tomcat源码" scheme="http://zhengweishan.oschina.io/categories/Tomcat%E6%BA%90%E7%A0%81/"/>
<category term="tomcat" scheme="http://zhengweishan.oschina.io/tags/tomcat/"/>
</entry>
<entry>
<title>kafka学习(四)---- Kafka整合SpringMVC实例(二)</title>
<link href="http://zhengweishan.oschina.io/2017/02/04/kafka%E5%AD%A6%E4%B9%A0%EF%BC%88%E5%9B%9B%EF%BC%89----%20Kafka%E6%95%B4%E5%90%88SpringMVC%E5%AE%9E%E4%BE%8B%EF%BC%88%E4%BA%8C%EF%BC%89/"/>
<id>http://zhengweishan.oschina.io/2017/02/04/kafka学习(四)---- Kafka整合SpringMVC实例(二)/</id>
<published>2017-02-03T16:00:00.000Z</published>
<updated>2017-03-01T08:46:49.305Z</updated>
<content type="html"><![CDATA[<h2 id="1、概述"><a href="#1、概述" class="headerlink" title="1、概述"></a>1、概述</h2><p>目前没有很好的整合Kafka的案例,自己参考着使用spring-integration-kafka框架写了一个:<br><a href="http://my.oschina.net/zhengweishan/blog/736213" target="_blank" rel="external">Kafka整合SpringMVC实例</a>,但同时也发现官方文档也不全,所以又用spring简单的实现了一下,感觉这个比使用spring-integration-kafka框架更简单一点,但是需要对kafka作深入的了解,废话不多说直接切入正题。</p>
<h2 id="2、实例"><a href="#2、实例" class="headerlink" title="2、实例"></a>2、实例</h2><p><strong>1. 安装Zookeeper</strong></p>
<p><a href="http://my.oschina.net/zhengweishan/blog/693163" target="_blank" rel="external">Zookeeper下载基本使用</a></p>
<p><strong>2. 安装Kafka</strong></p>
<p><a href="http://my.oschina.net/zhengweishan/blog/731330" target="_blank" rel="external">kafka基本概念以及环境搭建</a></p>
<a id="more"></a>
<p><strong>3. 创建spring项目(建议使用maven方式创建)</strong></p>
<blockquote>
<p>项目截图(小红叉不影响项目的启动)</p>
</blockquote>
<p><img src="http://i.imgur.com/wTOil58.png" alt=""></p>
<blockquote>
<p>pom.xml配置</p>
</blockquote>
<pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.kafka.demo&lt;/groupId&gt;
&lt;artifactId&gt;SpringWithKafka&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;SpringWithKafka Maven Webapp&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;
&lt;properties&gt;
&lt;spring.version&gt;4.2.5.RELEASE&lt;/spring.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.11&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;3.1.0&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;!-- spring --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-core&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-web&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- spring-kafka --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;
&lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;
&lt;version&gt;1.0.3.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- 日志 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-logging&lt;/groupId&gt;
&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
&lt;version&gt;1.1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;
&lt;version&gt;1.7.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax&lt;/groupId&gt;
&lt;artifactId&gt;javaee-api&lt;/artifactId&gt;
&lt;version&gt;7.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-core&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;finalName&gt;SpringWithKafka&lt;/finalName&gt;
&lt;/build&gt;
&lt;/project&gt;
</code></pre><blockquote>
<p>kafka-producer.xml配置</p>
</blockquote>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
&lt;context:property-placeholder location=&quot;classpath:init.properties&quot; /&gt;
&lt;!-- 定义producer的参数 --&gt;
&lt;bean id=&quot;producerProperties&quot; class=&quot;java.util.HashMap&quot;&gt;
&lt;constructor-arg&gt;
&lt;map&gt;
&lt;entry key=&quot;bootstrap.servers&quot; value=&quot;${bootstrap.servers}&quot;/&gt;
&lt;entry key=&quot;group.id&quot; value=&quot;0&quot;/&gt;
&lt;entry key=&quot;retries&quot; value=&quot;10&quot;/&gt;
&lt;entry key=&quot;batch.size&quot; value=&quot;16384&quot;/&gt;
&lt;entry key=&quot;linger.ms&quot; value=&quot;1&quot;/&gt;
&lt;entry key=&quot;buffer.memory&quot; value=&quot;33554432&quot;/&gt;
&lt;entry key=&quot;key.serializer&quot; value=&quot;org.apache.kafka.common.serialization.IntegerSerializer&quot;/&gt;
&lt;entry key=&quot;value.serializer&quot; value=&quot;org.apache.kafka.common.serialization.StringSerializer&quot;/&gt;
&lt;/map&gt;
&lt;/constructor-arg&gt;
&lt;/bean&gt;
&lt;!-- 创建kafkatemplate需要使用的producerfactory bean --&gt;
&lt;bean id=&quot;producerFactory&quot; class=&quot;org.springframework.kafka.core.DefaultKafkaProducerFactory&quot;&gt;
&lt;constructor-arg&gt;
&lt;ref bean=&quot;producerProperties&quot;/&gt;
&lt;/constructor-arg&gt;
&lt;/bean&gt;
&lt;!-- 创建kafkatemplate,使用的时候,只需要注入这个bean,即可使用template的send消息方法 --&gt;
&lt;bean id=&quot;KafkaTemplate&quot; class=&quot;org.springframework.kafka.core.KafkaTemplate&quot;&gt;
&lt;constructor-arg ref=&quot;producerFactory&quot;/&gt;
&lt;constructor-arg name=&quot;autoFlush&quot; value=&quot;true&quot;/&gt;
&lt;property name=&quot;defaultTopic&quot; value=&quot;myTopic&quot;/&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre><blockquote>
<p>kafka-consumer.xml配置 </p>
</blockquote>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;
&lt;context:property-placeholder location=&quot;classpath:init.properties&quot; /&gt;
&lt;!-- 定义consumer的参数 --&gt;
&lt;bean id=&quot;consumerProperties&quot; class=&quot;java.util.HashMap&quot;&gt;
&lt;constructor-arg&gt;
&lt;map&gt;
&lt;entry key=&quot;bootstrap.servers&quot; value=&quot;${bootstrap.servers}&quot;/&gt;
&lt;entry key=&quot;group.id&quot; value=&quot;0&quot;/&gt;
&lt;entry key=&quot;enable.auto.commit&quot; value=&quot;true&quot;/&gt;
&lt;entry key=&quot;auto.commit.interval.ms&quot; value=&quot;1000&quot;/&gt;
&lt;entry key=&quot;session.timeout.ms&quot; value=&quot;15000&quot;/&gt;
&lt;entry key=&quot;key.deserializer&quot; value=&quot;org.apache.kafka.common.serialization.IntegerDeserializer&quot;/&gt;
&lt;entry key=&quot;value.deserializer&quot; value=&quot;org.apache.kafka.common.serialization.StringDeserializer&quot;/&gt;
&lt;/map&gt;
&lt;/constructor-arg&gt;
&lt;/bean&gt;
&lt;!-- 创建consumerFactory bean --&gt;
&lt;bean id=&quot;consumerFactory&quot; class=&quot;org.springframework.kafka.core.DefaultKafkaConsumerFactory&quot;&gt;
&lt;constructor-arg&gt;
&lt;ref bean=&quot;consumerProperties&quot;/&gt;
&lt;/constructor-arg&gt;
&lt;/bean&gt;
&lt;!-- 实际执行消息消费的类 --&gt;
&lt;bean id=&quot;messageListernerConsumerService&quot; class=&quot;com.kafka.demo.service.KafkaConsumerService&quot;/&gt;
&lt;!-- 消费者容器配置信息 --&gt;
&lt;bean id=&quot;containerProperties&quot; class=&quot;org.springframework.kafka.listener.config.ContainerProperties&quot;&gt;
&lt;constructor-arg value=&quot;myTopic&quot;/&gt;
&lt;property name=&quot;messageListener&quot; ref=&quot;messageListernerConsumerService&quot;/&gt;
&lt;/bean&gt;
&lt;!-- 注册消费者容器到监听器 --&gt;
&lt;bean id=&quot;messageListenerContainer&quot; class=&quot;org.springframework.kafka.listener.KafkaMessageListenerContainer&quot; init-method=&quot;doStart&quot;&gt;
&lt;constructor-arg ref=&quot;consumerFactory&quot;/&gt;
&lt;constructor-arg ref=&quot;containerProperties&quot;/&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre><p>其他代码请参看实例源码:<a href="http://git.oschina.net/zhengweishan/Kafka_study_demo" target="_blank" rel="external">源码下载</a></p>
<h2 id="三、实例演示"><a href="#三、实例演示" class="headerlink" title="三、实例演示"></a>三、实例演示</h2><p>a、运行项目访问 <a href="http://localhost:8080/SpringMvcWithKafka/kafka/test" target="_blank" rel="external">http://localhost:8080/SpringMvcWithKafka/kafka/test</a> //测试地址<br>效果如图:</p>
<p><img src="http://i.imgur.com/H5UagCh.png" alt=""></p>
<p>b、查看kafka控制台信息输出,如下图:</p>
<p><img src="http://i.imgur.com/E1LMhg4.png" alt=""></p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、概述&quot;&gt;&lt;a href=&quot;#1、概述&quot; class=&quot;headerlink&quot; title=&quot;1、概述&quot;&gt;&lt;/a&gt;1、概述&lt;/h2&gt;&lt;p&gt;目前没有很好的整合Kafka的案例,自己参考着使用spring-integration-kafka框架写了一个:&lt;br&gt;&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/736213&quot;&gt;Kafka整合SpringMVC实例&lt;/a&gt;,但同时也发现官方文档也不全,所以又用spring简单的实现了一下,感觉这个比使用spring-integration-kafka框架更简单一点,但是需要对kafka作深入的了解,废话不多说直接切入正题。&lt;/p&gt;
&lt;h2 id=&quot;2、实例&quot;&gt;&lt;a href=&quot;#2、实例&quot; class=&quot;headerlink&quot; title=&quot;2、实例&quot;&gt;&lt;/a&gt;2、实例&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;1. 安装Zookeeper&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/693163&quot;&gt;Zookeeper下载基本使用&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. 安装Kafka&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/731330&quot;&gt;kafka基本概念以及环境搭建&lt;/a&gt;&lt;/p&gt;
</summary>
<category term="kafka" scheme="http://zhengweishan.oschina.io/categories/kafka/"/>
<category term="kafka" scheme="http://zhengweishan.oschina.io/tags/kafka/"/>
</entry>
<entry>
<title>kafka学习(三)----- Kafka整合SpringMVC实例</title>
<link href="http://zhengweishan.oschina.io/2017/02/03/kafka%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%89%EF%BC%89----%20Kafka%E6%95%B4%E5%90%88SpringMVC%E5%AE%9E%E4%BE%8B/"/>
<id>http://zhengweishan.oschina.io/2017/02/03/kafka学习(三)---- Kafka整合SpringMVC实例/</id>
<published>2017-02-02T16:00:00.000Z</published>
<updated>2017-03-01T08:44:20.839Z</updated>
<content type="html"><![CDATA[<h2 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h2><p>kafka一个高吞吐量的分布式发布订阅消息系统。有关知识请参看:<a href="http://my.oschina.net/zhengweishan/blog/731330" target="_blank" rel="external">kafka基本概念以及环境搭建</a>,kafka整合springMVC需要用到一个开源框架:<a href="https://github.com/spring-projects/spring-integration-kafka" target="_blank" rel="external">spring-integration-kafka</a>,这个官方框架我就不介绍了,请自行百度。</p>
<h2 id="二、实例"><a href="#二、实例" class="headerlink" title="二、实例"></a>二、实例</h2><p><strong>1. 安装Zookeeper</strong></p>
<p><a href="http://my.oschina.net/zhengweishan/blog/693163" target="_blank" rel="external">Zookeeper下载基本使用</a></p>
<p><strong>2. 安装Kafka</strong></p>
<p><a href="http://my.oschina.net/zhengweishan/blog/731330" target="_blank" rel="external">kafka基本概念以及环境搭建</a><br><a id="more"></a></p>
<p><strong>3. 创建spring项目(建议使用maven方式创建)</strong></p>
<blockquote>
<p>项目截图(小红叉不影响项目的启动)</p>
</blockquote>
<p><img src="http://i.imgur.com/mzhKhlQ.png" alt=""></p>
<blockquote>
<p>pom.xml配置 </p>
</blockquote>
<pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.kafka.demo&lt;/groupId&gt;
&lt;artifactId&gt;SpringMvcWithKafka&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;SpringMvcWithKafka Maven Webapp&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;
&lt;properties&gt;
&lt;spring.version&gt;4.2.5.RELEASE&lt;/spring.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;4.11&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;3.1.0&lt;/version&gt;
&lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-core&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-web&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;${spring.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.integration&lt;/groupId&gt;
&lt;artifactId&gt;spring-integration-kafka&lt;/artifactId&gt;
&lt;version&gt;1.3.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;commons-logging&lt;/groupId&gt;
&lt;artifactId&gt;commons-logging&lt;/artifactId&gt;
&lt;version&gt;1.1.1&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.slf4j&lt;/groupId&gt;
&lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt;
&lt;version&gt;1.7.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax&lt;/groupId&gt;
&lt;artifactId&gt;javaee-api&lt;/artifactId&gt;
&lt;version&gt;7.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-core&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt;
&lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.avro&lt;/groupId&gt;
&lt;artifactId&gt;avro&lt;/artifactId&gt;
&lt;version&gt;1.7.7&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;finalName&gt;SpringMvcWithKafka&lt;/finalName&gt;
&lt;/build&gt;
&lt;/project&gt;
</code></pre><blockquote>
<p>spring-kafka-consumer.xml配置</p>
</blockquote>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:int=&quot;http://www.springframework.org/schema/integration&quot;
xmlns:int-kafka=&quot;http://www.springframework.org/schema/integration/kafka&quot;
xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/integration/kafka
http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd&quot;&gt;
&lt;!-- topic test conf --&gt;
&lt;int:channel id=&quot;inputFromKafka&quot;&gt;
&lt;int:dispatcher task-executor=&quot;kafkaMessageExecutor&quot; /&gt;
&lt;/int:channel&gt;
&lt;!-- zookeeper配置 可以配置多个 --&gt;
&lt;int-kafka:zookeeper-connect id=&quot;zookeeperConnect&quot;
zk-connect=&quot;localhost:2181&quot; zk-connection-timeout=&quot;6000&quot;
zk-session-timeout=&quot;6000&quot; zk-sync-time=&quot;2000&quot; /&gt;
&lt;!-- channel配置 auto-startup=&quot;true&quot; 否则接收不发数据 --&gt;
&lt;int-kafka:inbound-channel-adapter
id=&quot;kafkaInboundChannelAdapter&quot; kafka-consumer-context-ref=&quot;consumerContext&quot;
auto-startup=&quot;true&quot; channel=&quot;inputFromKafka&quot;&gt;
&lt;int:poller fixed-delay=&quot;1&quot; time-unit=&quot;MILLISECONDS&quot; /&gt;
&lt;/int-kafka:inbound-channel-adapter&gt;
&lt;task:executor id=&quot;kafkaMessageExecutor&quot; pool-size=&quot;8&quot; keep-alive=&quot;120&quot; queue-capacity=&quot;500&quot; /&gt;
&lt;bean id=&quot;kafkaDecoder&quot; class=&quot;org.springframework.integration.kafka.serializer.common.StringDecoder&quot; /&gt;
&lt;bean id=&quot;consumerProperties&quot;
class=&quot;org.springframework.beans.factory.config.PropertiesFactoryBean&quot;&gt;
&lt;property name=&quot;properties&quot;&gt;
&lt;props&gt;
&lt;prop key=&quot;auto.offset.reset&quot;&gt;smallest&lt;/prop&gt;
&lt;prop key=&quot;socket.receive.buffer.bytes&quot;&gt;10485760&lt;/prop&gt; &lt;!-- 10M --&gt;
&lt;prop key=&quot;fetch.message.max.bytes&quot;&gt;5242880&lt;/prop&gt;
&lt;prop key=&quot;auto.commit.interval.ms&quot;&gt;1000&lt;/prop&gt;
&lt;/props&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!-- 消息接收的BEEN --&gt;
&lt;bean id=&quot;kafkaConsumerService&quot; class=&quot;com.kafka.demo.service.impl.KafkaConsumerService&quot; /&gt;
&lt;!-- 指定接收的方法 --&gt;
&lt;int:outbound-channel-adapter channel=&quot;inputFromKafka&quot;
ref=&quot;kafkaConsumerService&quot; method=&quot;processMessage&quot; /&gt;
&lt;int-kafka:consumer-context id=&quot;consumerContext&quot;
consumer-timeout=&quot;1000&quot; zookeeper-connect=&quot;zookeeperConnect&quot;
consumer-properties=&quot;consumerProperties&quot;&gt;
&lt;int-kafka:consumer-configurations&gt;
&lt;int-kafka:consumer-configuration
group-id=&quot;default1&quot; value-decoder=&quot;kafkaDecoder&quot; key-decoder=&quot;kafkaDecoder&quot;
max-messages=&quot;5000&quot;&gt;
&lt;!-- 两个TOPIC配置 --&gt;
&lt;int-kafka:topic id=&quot;myTopic&quot; streams=&quot;4&quot; /&gt;
&lt;int-kafka:topic id=&quot;testTopic&quot; streams=&quot;4&quot; /&gt;
&lt;/int-kafka:consumer-configuration&gt;
&lt;/int-kafka:consumer-configurations&gt;
&lt;/int-kafka:consumer-context&gt;
&lt;/beans&gt;
</code></pre><blockquote>
<p>spring-kafka-producer.xml配置</p>
</blockquote>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:int=&quot;http://www.springframework.org/schema/integration&quot;
xmlns:int-kafka=&quot;http://www.springframework.org/schema/integration/kafka&quot;
xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/integration/kafka http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd&quot;&gt;
&lt;!-- commons config --&gt;
&lt;bean id=&quot;stringSerializer&quot; class=&quot;org.apache.kafka.common.serialization.StringSerializer&quot; /&gt;
&lt;bean id=&quot;kafkaEncoder&quot;
class=&quot;org.springframework.integration.kafka.serializer.avro.AvroReflectDatumBackedKafkaEncoder&quot;&gt;
&lt;constructor-arg value=&quot;java.lang.String&quot; /&gt;
&lt;/bean&gt;
&lt;bean id=&quot;producerProperties&quot;
class=&quot;org.springframework.beans.factory.config.PropertiesFactoryBean&quot;&gt;
&lt;property name=&quot;properties&quot;&gt;
&lt;props&gt;
&lt;prop key=&quot;topic.metadata.refresh.interval.ms&quot;&gt;3600000&lt;/prop&gt;
&lt;prop key=&quot;message.send.max.retries&quot;&gt;5&lt;/prop&gt;
&lt;prop key=&quot;serializer.class&quot;&gt;kafka.serializer.StringEncoder&lt;/prop&gt;
&lt;prop key=&quot;request.required.acks&quot;&gt;1&lt;/prop&gt;
&lt;/props&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!-- topic test config --&gt;
&lt;int:channel id=&quot;kafkaTopicTest&quot;&gt;
&lt;int:queue /&gt;
&lt;/int:channel&gt;
&lt;int-kafka:outbound-channel-adapter
id=&quot;kafkaOutboundChannelAdapterTopicTest&quot; kafka-producer-context-ref=&quot;producerContextTopicTest&quot;
auto-startup=&quot;true&quot; channel=&quot;kafkaTopicTest&quot; order=&quot;3&quot;&gt;
&lt;int:poller fixed-delay=&quot;1000&quot; time-unit=&quot;MILLISECONDS&quot;
receive-timeout=&quot;1&quot; task-executor=&quot;taskExecutor&quot; /&gt;
&lt;/int-kafka:outbound-channel-adapter&gt;
&lt;task:executor id=&quot;taskExecutor&quot; pool-size=&quot;5&quot;
keep-alive=&quot;120&quot; queue-capacity=&quot;500&quot; /&gt;
&lt;int-kafka:producer-context id=&quot;producerContextTopicTest&quot;
producer-properties=&quot;producerProperties&quot;&gt;
&lt;int-kafka:producer-configurations&gt;
&lt;!-- 多个topic配置 --&gt;
&lt;int-kafka:producer-configuration
broker-list=&quot;localhost:9092&quot; key-serializer=&quot;stringSerializer&quot;
value-class-type=&quot;java.lang.String&quot; value-serializer=&quot;stringSerializer&quot;
topic=&quot;testTopic&quot; /&gt;
&lt;int-kafka:producer-configuration
broker-list=&quot;localhost:9092&quot; key-serializer=&quot;stringSerializer&quot;
value-class-type=&quot;java.lang.String&quot; value-serializer=&quot;stringSerializer&quot;
topic=&quot;myTopic&quot; /&gt;
&lt;/int-kafka:producer-configurations&gt;
&lt;/int-kafka:producer-context&gt;
&lt;/beans&gt;
</code></pre><p>其他代码请参看实例源码:<a href="http://git.oschina.net/zhengweishan/Kafka_study_demo" target="_blank" rel="external">源码下载</a></p>
<h2 id="三、实例演示"><a href="#三、实例演示" class="headerlink" title="三、实例演示"></a>三、实例演示</h2><p>a、先根据配置文件使用命令行创建两个topic,截图如下:</p>
<p><img src="http://i.imgur.com/w4q0VZE.png" alt=""></p>
<p>b、运行项目访问 <a href="http://localhost:8080/SpringMvcWithKafka/kafka/test" target="_blank" rel="external">http://localhost:8080/SpringMvcWithKafka/kafka/test</a> //测试地址<br>效果如图:</p>
<p><img src="http://i.imgur.com/aXG3zKL.png" alt=""></p>
<p>c、查看kafka控制台信息输出,如下图:</p>
<p><img src="http://i.imgur.com/QzFa2Je.png" alt=""></p>
<p>说明:如果使用最新版本的kafka,上面的例子可能就跑步起来了,猜测应该是kafka版本问题,所以推荐使用稳定版本。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;一、概述&quot;&gt;&lt;a href=&quot;#一、概述&quot; class=&quot;headerlink&quot; title=&quot;一、概述&quot;&gt;&lt;/a&gt;一、概述&lt;/h2&gt;&lt;p&gt;kafka一个高吞吐量的分布式发布订阅消息系统。有关知识请参看:&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/731330&quot;&gt;kafka基本概念以及环境搭建&lt;/a&gt;,kafka整合springMVC需要用到一个开源框架:&lt;a href=&quot;https://github.com/spring-projects/spring-integration-kafka&quot;&gt;spring-integration-kafka&lt;/a&gt;,这个官方框架我就不介绍了,请自行百度。&lt;/p&gt;
&lt;h2 id=&quot;二、实例&quot;&gt;&lt;a href=&quot;#二、实例&quot; class=&quot;headerlink&quot; title=&quot;二、实例&quot;&gt;&lt;/a&gt;二、实例&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;1. 安装Zookeeper&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/693163&quot;&gt;Zookeeper下载基本使用&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;2. 安装Kafka&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/731330&quot;&gt;kafka基本概念以及环境搭建&lt;/a&gt;&lt;br&gt;
</summary>
<category term="kafka" scheme="http://zhengweishan.oschina.io/categories/kafka/"/>
<category term="kafka" scheme="http://zhengweishan.oschina.io/tags/kafka/"/>
</entry>
<entry>
<title>kafka学习(二)---- Kafka简单的Java版本的Hello World实例</title>
<link href="http://zhengweishan.oschina.io/2017/02/02/kafka%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%BA%8C%EF%BC%89----%20Kafka%E7%AE%80%E5%8D%95%E7%9A%84Java%E7%89%88%E6%9C%AC%E7%9A%84HelloWorld%E5%AE%9E%E4%BE%8B/"/>
<id>http://zhengweishan.oschina.io/2017/02/02/kafka学习(二)---- Kafka简单的Java版本的HelloWorld实例/</id>
<published>2017-02-01T16:00:00.000Z</published>
<updated>2017-03-01T08:41:22.175Z</updated>
<content type="html"><![CDATA[<h2 id="1、开发环境"><a href="#1、开发环境" class="headerlink" title="1、开发环境"></a>1、开发环境</h2><p>我使用的是官网的kafka_2.11-0.10.0.0版本,最新的是kafka_2.11-0.10.0.1版本,大家自行下载安装配置。<a href="http://kafka.apache.org/downloads.html" target="_blank" rel="external">点击进入下载地址</a>,<a href="http://my.oschina.net/zhengweishan/blog/731330" target="_blank" rel="external">点击进入如何win下配置开发环境</a></p>
<p>##2、 创建项目 ##<br>两种方式:</p>
<p><strong>(a)普通的方式创建</strong></p>
<blockquote>
<p>注意:开发时候,需要将下载kafka-2.11-0.10.0.0.jar包加入到classpath下面,这个包包含了所有Kafka的api的实现。由于kafka是使用Scala编写的,所以可能下载的kafka中的libs文件中的kafka-2.11-0.10.0.0.jar放到项目中不能用,而且还依赖scala-library-2.11.8.jar,所以推荐使用第二种方式构建项目。</p>
</blockquote>
<p>项目结构图:</p>
<p><img src="http://i.imgur.com/Jjzv5Gv.png" alt=""></p>
<p><strong>(b)maven构建项目</strong><br>maven下载配置这里不再叙述,请参看:<a href="http://my.oschina.net/zhengweishan/blog/690195" target="_blank" rel="external">eclipse创建maven多模块项目</a>中有关maven的介绍。好处在于不用自己去添加依赖了,maven自己帮我们加载依赖。</p>
<p>项目结构图:</p>
<p><img src="http://i.imgur.com/R74N0K3.png" alt=""></p>
<a id="more"></a>
<h2 id="3、实例源码"><a href="#3、实例源码" class="headerlink" title="3、实例源码"></a>3、实例源码</h2><h3 id="3-1-生产者"><a href="#3-1-生产者" class="headerlink" title="3.1 生产者"></a>3.1 生产者</h3><pre><code>package com.kafka.demo;
import java.util.Date;
import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
/**
* @see https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+Producer+Example
* @see http://kafka.apache.org/documentation.html#producerapi
* @author wesley
*
*/
public class ProducerDemo {
@SuppressWarnings(&quot;deprecation&quot;)
public static void main(String[] args) {
int events = 20;
// @see http://kafka.apache.org/08/configuration.html-- 3.3 Producer
// Configs
// @see http://kafka.apache.org/documentation.html#producerconfigs
// 设置配置属性
Properties props = new Properties();
props.put(&quot;metadata.broker.list&quot;, &quot;127.0.0.1:9092&quot;); // 配置kafka的IP和端口
props.put(&quot;serializer.class&quot;, &quot;kafka.serializer.StringEncoder&quot;);
// key.serializer.class默认为serializer.class
props.put(&quot;key.serializer.class&quot;, &quot;kafka.serializer.StringEncoder&quot;);
// 可选配置,如果不配置,则使用默认的partitioner
props.put(&quot;partitioner.class&quot;, &quot;com.kafka.demo.PartitionerDemo&quot;);
// 触发acknowledgement机制,否则是fire and forget,可能会引起数据丢失
// 值为0,1,-1,可以参考
props.put(&quot;request.required.acks&quot;, &quot;1&quot;);
ProducerConfig config = new ProducerConfig(props);
// 创建producer
Producer&lt;String, String&gt; producer = new Producer&lt;String, String&gt;(config);
// 产生并发送消息
long start = System.currentTimeMillis();
for (long i = 0; i &lt; events; i++) {
long runtime = new Date().getTime();
String ip = &quot;192.168.1.&quot; + i;
String msg = runtime + &quot;--www.kafkademo.com--&quot; + ip;
// 如果topic不存在,则会自动创建,默认replication-factor为1,partitions为0
KeyedMessage&lt;String, String&gt; data = new KeyedMessage&lt;String, String&gt;(&quot;page_visits&quot;, ip, msg);
System.out.println(&quot;-----Kafka Producer----createMessage----&quot; + data);
producer.send(data);
}
System.out.println(&quot;Time consuming:&quot; + (System.currentTimeMillis() - start));
// 关闭producer
producer.close();
}
}
</code></pre><h3 id="3-2-生产者需要配置的Partition类"><a href="#3-2-生产者需要配置的Partition类" class="headerlink" title="3.2 生产者需要配置的Partition类"></a>3.2 生产者需要配置的Partition类</h3><pre><code>package com.kafka.demo;
import kafka.producer.Partitioner;
import kafka.utils.VerifiableProperties;
@SuppressWarnings(&quot;deprecation&quot;)
public class PartitionerDemo implements Partitioner {
public PartitionerDemo (VerifiableProperties props) {
}
public int partition(Object key, int a_numPartitions) {
int partition = 0;
String stringKey = (String) key;
int offset = stringKey.lastIndexOf(&apos;.&apos;);
if (offset &gt; 0) {
partition = Integer.parseInt( stringKey.substring(offset+1)) % a_numPartitions;
}
return partition;
}
}
</code></pre><h4 id="运行之后的效果:"><a href="#运行之后的效果:" class="headerlink" title="运行之后的效果:"></a>运行之后的效果:</h4><p><img src="http://i.imgur.com/EAEoUzo.png" alt=""></p>
<h4 id="查看控制台:"><a href="#查看控制台:" class="headerlink" title="查看控制台:"></a>查看控制台:</h4><p><img src="http://i.imgur.com/TV4V8aL.png" alt=""></p>
<blockquote>
<p>红色部分就是新生成的待消费的信息。</p>
</blockquote>
<h3 id="3-3-消费者-单线程实例"><a href="#3-3-消费者-单线程实例" class="headerlink" title="3.3 消费者(单线程实例)"></a>3.3 消费者(单线程实例)</h3><pre><code>package com.kafka.demo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
/**
* @see http://kafka.apache.org/documentation.html#consumerapi
* @see https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example
* @see https://cwiki.apache.org/confluence/display/KAFKA/0.8.0+SimpleConsumer+Example
* @author wesley
*
*/
public class ConsumerSimpleDemo extends Thread {
// 消费者连接
private final ConsumerConnector consumer;
// 要消费的话题
private final String topic;
public ConsumerSimpleDemo(String topic) {
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(createConsumerConfig());
this.topic = topic;
}
// 配置相关信息
private static ConsumerConfig createConsumerConfig() {
Properties props = new Properties();
// props.put(&quot;zookeeper.connect&quot;,&quot;localhost:2181,10.XX.XX.XX:2181,10.XX.XX.XX:2181&quot;);
// 配置要连接的zookeeper地址与端口
props.put(&quot;zookeeper.connect&quot;, &quot;127.0.0.1:2181&quot;);
// 配置zookeeper的组id
props.put(&quot;group.id&quot;, &quot;group-1&quot;);
// 配置zookeeper连接超时间隔
props.put(&quot;zookeeper.session.timeout.ms&quot;, &quot;10000&quot;);
// 配置zookeeper异步执行时间
props.put(&quot;zookeeper.sync.time.ms&quot;, &quot;200&quot;);
// 配置自动提交时间间隔
props.put(&quot;auto.commit.interval.ms&quot;, &quot;1000&quot;);
return new ConsumerConfig(props);
}
public void run() {
Map&lt;String, Integer&gt; topickMap = new HashMap&lt;String, Integer&gt;();
topickMap.put(topic, 1);
Map&lt;String, List&lt;KafkaStream&lt;byte[], byte[]&gt;&gt;&gt; streamMap = consumer.createMessageStreams(topickMap);
KafkaStream&lt;byte[], byte[]&gt; stream = streamMap.get(topic).get(0);
ConsumerIterator&lt;byte[], byte[]&gt; it = stream.iterator();
System.out.println(&quot;*********Results********&quot;);
while (true) {
if (it.hasNext()) {
// 打印得到的消息
System.err.println(Thread.currentThread() + &quot; get data:&quot; + new String(it.next().message()));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ConsumerSimpleDemo consumerThread = new ConsumerSimpleDemo(&quot;page_visits&quot;);
consumerThread.start();
}
}
</code></pre><h4 id="运行之后的效果:-1"><a href="#运行之后的效果:-1" class="headerlink" title="运行之后的效果:"></a>运行之后的效果:</h4><p><img src="http://i.imgur.com/TGZSlHp.png" alt=""></p>
<h3 id="3-4-消费者-线程池实例"><a href="#3-4-消费者-线程池实例" class="headerlink" title="3.4 消费者(线程池实例)"></a>3.4 消费者(线程池实例)</h3><pre><code>package com.kafka.demo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
/* https://cwiki.apache.org/confluence/display/KAFKA/Consumer+Group+Example
* http://kafka.apache.org/documentation.html#consumerapi
*/
public class ConsumerDemo {
private final ConsumerConnector consumer;
private final String topic;
private ExecutorService executor;
public ConsumerDemo(String a_zookeeper, String a_groupId, String a_topic) {
consumer = Consumer.createJavaConsumerConnector(createConsumerConfig(a_zookeeper,a_groupId));
this.topic = a_topic;
}
public void shutdown() {
if (consumer != null)
consumer.shutdown();
if (executor != null)
executor.shutdown();
try {
if (!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)) {
System.out.println(&quot;Timed out waiting for consumer threads to shut down, exiting uncleanly&quot;);
}
} catch (InterruptedException e) {
System.out.println(&quot;Interrupted during shutdown, exiting uncleanly&quot;);
}
}
public void run(int numThreads) {
System.out.println(&quot;-----Consumers begin to execute-------&quot;);
Map&lt;String, Integer&gt; topicCountMap = new HashMap&lt;String, Integer&gt;();
topicCountMap.put(topic, new Integer(numThreads));
Map&lt;String, List&lt;KafkaStream&lt;byte[], byte[]&gt;&gt;&gt; consumerMap = consumer
.createMessageStreams(topicCountMap);
List&lt;KafkaStream&lt;byte[], byte[]&gt;&gt; streams = consumerMap.get(topic);
System.err.println(&quot;-----Need to consume content----&quot;+streams);
// now launch all the threads
executor = Executors.newFixedThreadPool(numThreads);
// now create an object to consume the messages
int threadNumber = 0;
for (final KafkaStream&lt;byte[], byte[]&gt; stream : streams) {
System.out.println(&quot;-----Consumers begin to consume-------&quot;+stream);
executor.submit(new ConsumerMsgTask(stream, threadNumber));
threadNumber++;
}
}
private static ConsumerConfig createConsumerConfig(String a_zookeeper,
String a_groupId) {
Properties props = new Properties();
// see http://kafka.apache.org/08/configuration.html --3.2 Consumer Configs
// http://kafka.apache.org/documentation.html#consumerconfigs
props.put(&quot;zookeeper.connect&quot;, a_zookeeper); //配置ZK地址
props.put(&quot;group.id&quot;, a_groupId); //必填字段
props.put(&quot;zookeeper.session.timeout.ms&quot;, &quot;400&quot;);
props.put(&quot;zookeeper.sync.time.ms&quot;, &quot;200&quot;);
props.put(&quot;auto.commit.interval.ms&quot;, &quot;1000&quot;);
return new ConsumerConfig(props);
}
public static void main(String[] arg) {
String[] args = { &quot;127.0.0.1:2181&quot;, &quot;group-1&quot;, &quot;page_visits&quot;, &quot;10&quot; };
String zooKeeper = args[0];
String groupId = args[1];
String topic = args[2];
int threads = Integer.parseInt(args[3]);
ConsumerDemo demo = new ConsumerDemo(zooKeeper, groupId, topic);
demo.run(threads);
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
}
demo.shutdown();
}
}
</code></pre><blockquote>
<p>注意:这里要调用处理消息的类</p>
</blockquote>
<h3 id="3-5-处理消息的类"><a href="#3-5-处理消息的类" class="headerlink" title="3.5 处理消息的类"></a>3.5 处理消息的类</h3><pre><code>package com.kafka.demo;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
public class ConsumerMsgTask implements Runnable {
private KafkaStream&lt;byte[], byte[]&gt; m_stream;
private int m_threadNumber;
public ConsumerMsgTask(KafkaStream&lt;byte[], byte[]&gt; stream, int threadNumber) {
m_threadNumber = threadNumber;
m_stream = stream;
}
public void run() {
System.out.println(&quot;-----Consumers begin to consume-------&quot;);
ConsumerIterator&lt;byte[], byte[]&gt; it = m_stream.iterator();
while (it.hasNext()){
System.out.println(&quot;Thread &quot; + m_threadNumber + &quot;: &quot;+ new String(it.next().message()));
}
System.out.println(&quot;Shutting down Thread: &quot; + m_threadNumber);
}
}
</code></pre><h4 id="运行效果图:"><a href="#运行效果图:" class="headerlink" title="运行效果图:"></a>运行效果图:</h4><p><img src="http://i.imgur.com/t4OVBh1.png" alt=""></p>
<p><img src="http://i.imgur.com/DujHiGq.png" alt=""></p>
<p><img src="http://i.imgur.com/42cPZ1T.png" alt=""></p>
<p>实例到此结束,大家可以多看看kafka的文档,多了解一些kafka的知识,这里只是演示了怎么用,其实也都是文档中的东西,自己总结了一下。</p>
<p><strong>说明</strong>:</p>
<p>为什么使用High Level Consumer?</p>
<p>有些场景下,从Kafka中读取消息的逻辑不处理消息的offset,仅仅是获取消息数据。High Level Consumer就提供了这种功能。首先要知道的是,High Level Consumer在ZooKeeper上保存最新的offset(从指定的分区中读取)。这个offset基于consumer group名存储。Consumer group名在Kafka集群上是全局性的,在启动新的consumer group的时候要小心集群上没有关闭的consumer。当一个consumer线程启动了,Kafka会将它加入到相同的topic下的相同consumer group里,并且触发重新分配。在重新分配时,Kafka将partition分配给consumer,有可能会移动一个partition给另一个consumer。如果老的、新的处理逻辑同时存在,有可能一些消息传递到了老的consumer上。使用High LevelConsumer首先要知道的是,它应该是多线程的。消费者线程的数量跟tipic的partition数量有关,它们之间有一些特定的规则:</p>
<ul>
<li><p>如果线程数量大于主题的分区数量,一些线程将得不到任何消息</p>
</li>
<li><p>如果分区数大于线程数,一些线程将得到多个分区的消息</p>
</li>
<li><p>如果一个线程处理多个分区的消息,它接收到消息的顺序是不能保证的。比如,先从分区10获取了5条消息,从分区11获取了6条消息,然后从分区10获取了5条,紧接着又从分区10获取了5条,虽然分区11还有消息。</p>
</li>
<li><p>添加更多了同consumer group的consumer将触发Kafka重新分配,某个分区本来分配给a线程的,从新分配后,有可能分配给了b线程。</p>
</li>
</ul>
<h2 id="4、参考资料:"><a href="#4、参考资料:" class="headerlink" title="4、参考资料:"></a>4、参考资料:</h2><ol>
<li><a href="http://kafka.apache.org/documentation.html" target="_blank" rel="external">http://kafka.apache.org/documentation.html</a></li>
<li><a href="https://cwiki.apache.org/confluence/display/KAFKA/Index" target="_blank" rel="external">https://cwiki.apache.org/confluence/display/KAFKA/Index</a></li>
</ol>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、开发环境&quot;&gt;&lt;a href=&quot;#1、开发环境&quot; class=&quot;headerlink&quot; title=&quot;1、开发环境&quot;&gt;&lt;/a&gt;1、开发环境&lt;/h2&gt;&lt;p&gt;我使用的是官网的kafka_2.11-0.10.0.0版本,最新的是kafka_2.11-0.10.0.1版本,大家自行下载安装配置。&lt;a href=&quot;http://kafka.apache.org/downloads.html&quot;&gt;点击进入下载地址&lt;/a&gt;,&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/731330&quot;&gt;点击进入如何win下配置开发环境&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;##2、 创建项目 ##&lt;br&gt;两种方式:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;(a)普通的方式创建&lt;/strong&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;注意:开发时候,需要将下载kafka-2.11-0.10.0.0.jar包加入到classpath下面,这个包包含了所有Kafka的api的实现。由于kafka是使用Scala编写的,所以可能下载的kafka中的libs文件中的kafka-2.11-0.10.0.0.jar放到项目中不能用,而且还依赖scala-library-2.11.8.jar,所以推荐使用第二种方式构建项目。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;项目结构图:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/Jjzv5Gv.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;(b)maven构建项目&lt;/strong&gt;&lt;br&gt;maven下载配置这里不再叙述,请参看:&lt;a href=&quot;http://my.oschina.net/zhengweishan/blog/690195&quot;&gt;eclipse创建maven多模块项目&lt;/a&gt;中有关maven的介绍。好处在于不用自己去添加依赖了,maven自己帮我们加载依赖。&lt;/p&gt;
&lt;p&gt;项目结构图:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/R74N0K3.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</summary>
<category term="kafka" scheme="http://zhengweishan.oschina.io/categories/kafka/"/>
<category term="kafka" scheme="http://zhengweishan.oschina.io/tags/kafka/"/>
</entry>
<entry>
<title>kafka学习(一) ---- 基本概念以及环境搭建</title>
<link href="http://zhengweishan.oschina.io/2017/02/01/kafka%E5%AD%A6%E4%B9%A0(%E4%B8%80)%20----%20%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5%E4%BB%A5%E5%8F%8A%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA/"/>
<id>http://zhengweishan.oschina.io/2017/02/01/kafka学习(一) ---- 基本概念以及环境搭建/</id>
<published>2017-01-31T16:00:00.000Z</published>
<updated>2017-03-01T08:44:51.568Z</updated>
<content type="html"><![CDATA[<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>由于项目涉及到kafka,自己以前没有接触过这方面的,学习了下,将搭建kafka运行环境同大家分享(单机搭建的Windows下的运行环境,Linux下的由于懒得装虚拟机就没有搭建,以后有时间在分享一次,搭建这个环境就是只为了学习)。</p>
<h2 id="1、基本概念"><a href="#1、基本概念" class="headerlink" title="1、基本概念"></a>1、基本概念</h2><h3 id="1-1-什么是kafka"><a href="#1-1-什么是kafka" class="headerlink" title="1.1 什么是kafka"></a>1.1 什么是kafka</h3><blockquote>
<p>Apache Kafka is publish-subscribe messaging rethought as a distributed commit log。Kafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.//官方解释</p>
</blockquote>
<p>Kafka是一种高吞吐量的分布式发布订阅消息系统,它提供了类似于JMS的特性,但是在设计实现上完全不同,此外它并不是JMS规范的实现。kafka对消息保存时根据Topic进行归类,发送消息者成为Producer,消息接受者成为Consumer,此外kafka集群有多个kafka实例组成,每个实例(server)成为broker。无论是kafka集群,还是producer和consumer都依赖于zookeeper来保证系统可用性集群保存一些meta信息。<br>整体运行机制如下图:</p>
<p><img src="http://i.imgur.com/LmF8AIe.png" alt=""> </p>
<p>图来源于官网</p>
<p>更多内容请参看:<a href="http://kafka.apache.org/documentation.html" target="_blank" rel="external">官方文档</a>,这里就不一一翻译了。<br><a id="more"></a></p>
<h3 id="1-2-kafka的特点"><a href="#1-2-kafka的特点" class="headerlink" title="1.2 kafka的特点"></a>1.2 kafka的特点</h3><ul>
<li>通过I/O的磁盘数据结构提供消息的持久化,这种结构对于即使数以TB的消息存储也能够保持长时间的稳定性能。</li>
<li>高吞吐量:即使是非常普通的硬件Kafka也可以支持每秒数百万的消息。</li>
<li>支持通过Kafka服务器和消费机集群来分区消息。</li>
<li>支持Hadoop并行数据加载<h3 id="1-3-涉及的术语"><a href="#1-3-涉及的术语" class="headerlink" title="1.3 涉及的术语"></a>1.3 涉及的术语</h3></li>
<li>Broker<br>Kafka集群包含一个或多个服务器,这种服务器被称为broker</li>
<li>Topic<br>每条发布到Kafka集群的消息都有一个类别,这个类别被称为Topic。(物理上不同Topic的消息分开存储,逻辑上一个Topic的消息虽然保存于一个或多个broker上但用户只需指定消息的Topic即可生产或消费数据而不必关心数据存于何处)</li>
<li>Partition<br>Partition是物理上的概念,每个Topic包含一个或多个Partition.</li>
<li>Producer<br>负责发布消息到Kafka broker</li>
<li>Consumer<br>消息消费者,向Kafka broker读取消息的客户端。</li>
<li>Consumer Group<br>每个Consumer属于一个特定的Consumer Group(可为每个Consumer指定group name,若不指定group name则属于默认的group)</li>
</ul>
<h2 id="2、环境搭建"><a href="#2、环境搭建" class="headerlink" title="2、环境搭建"></a>2、环境搭建</h2><h3 id="2-1-下载"><a href="#2-1-下载" class="headerlink" title="2.1 下载"></a>2.1 下载</h3><p><a href="http://kafka.apache.org/downloads.html" target="_blank" rel="external">下载地址</a>:<a href="http://kafka.apache.org/downloads.html" target="_blank" rel="external">http://kafka.apache.org/downloads.html</a></p>
<p><img src="http://i.imgur.com/qvyQfPW.png" alt=""></p>
<h3 id="2-2-单机搭建win下的运行环境"><a href="#2-2-单机搭建win下的运行环境" class="headerlink" title="2.2 单机搭建win下的运行环境"></a>2.2 单机搭建win下的运行环境</h3><p>官网没有win版本的,下载之后直接按照Linux下解压缩一样,解压之后文件结构如下:</p>
<p><img src="http://i.imgur.com/tsVmV0m.png" alt=""></p>
<h4 id="2-2-1-配置kafka"><a href="#2-2-1-配置kafka" class="headerlink" title="2.2.1 配置kafka"></a>2.2.1 配置kafka</h4><ol>
<li>进入Kafka配置目录:S:\devTools\kafka_2.11-0.10.0.0\config</li>
<li>编辑文件“server.properties” 主要配置日志所在目录(也可以使用默认的)</li>
<li>找到并编辑“log.dirs=/tmp/kafka-logs” to “log.dirs= S:/devTools/kafka_2.11-0.10.0.0/kafka-logs”</li>
<li>如果Zookeeper在某些其他的机器或集群上运行,可以将“zookeeper.connect:2181”修改为自定义IP与端口。在这个演示中我们使用了同一个机器,因此没必要做修改。文件中的Kafka端口和broker.id也是可以配置的。其他设置不变。</li>
<li>Kafka会按照默认在9092端口上运行,并连接zookeeper的默认端口:2181。</li>
</ol>
<h4 id="2-2-2-运行kafka"><a href="#2-2-2-运行kafka" class="headerlink" title="2.2.2 运行kafka"></a>2.2.2 运行kafka</h4><blockquote>
<p>重要:请确保在启动Kafka服务器前,Zookeeper实例已经准备好并开始运行。</p>
</blockquote>
<p>Zookeeper如何安装运行请参看我的博客:<a href="http://my.oschina.net/zhengweishan/blog/693163" target="_blank" rel="external">Dubbo与Zookeeper、SpringMVC整合和使用</a>中有关Zookeeper的介绍。</p>
<p>kafka在win下的启动命令都在bin目录下的Windows文件下,如下图:<br><img src="http://i.imgur.com/RItJHpN.png" alt=""></p>
<p>不知道是不是win脚本问题,直接运行这些命令都是失败的启动不了kafka,没有办法还是cmd启动吧。</p>
<ol>
<li>进入Kafka安装目录S:\devTools\kafka_2.11-0.10.0.0\</li>
<li>按下Shift+右键,选择“打开命令窗口”选项,打开命令行。</li>
</ol>
<p><img src="http://i.imgur.com/B1PBz1G.png" alt=""></p>
<ol>
<li>现在输入.\bin\windows\kafka-server-start.bat .\config\server.properties 并回车。</li>
</ol>
<p><img src="http://i.imgur.com/Ti0yQRQ.png" alt=""></p>
<ol>
<li>如果一切正常,命令行应当是这样:</li>
</ol>
<p><img src="http://i.imgur.com/8D3ZPjY.png" alt=""></p>
<ol>
<li>现在Kafka已经准备好并开始运行,可以创建主题来存储消息了。我们也能从Java/Scala代码中,或直接从命令行中生成或使用数据。</li>
</ol>
<h4 id="2-2-3-创建主题"><a href="#2-2-3-创建主题" class="headerlink" title="2.2.3 创建主题"></a>2.2.3 创建主题</h4><ol>
<li>现在创建主题,命名为“demo”,replication factor=1(因为只有1个Kafka服务器在运行)。如果集群中所运行的Kafka服务器不止1个,可以相应增加replication-factor,从而提高数据可用性和系统容错性。</li>
<li>在S:\devTools\kafka_2.11-0.10.0.0\bin\windows打开新的命令行。</li>
<li>输入下面的命令,回车:<blockquote>
<p>kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic demo</p>
</blockquote>
</li>
</ol>
<p>结果如下:</p>
<p><img src="http://i.imgur.com/KwVpYhY.png" alt=""></p>
<h4 id="2-2-4-创建生产者"><a href="#2-2-4-创建生产者" class="headerlink" title="2.2.4 创建生产者"></a>2.2.4 创建生产者</h4><ol>
<li>在S:\devTools\kafka_2.11-0.10.0.0\bin\windows打开新的命令行。</li>
<li>输入下面的命令,回车:</li>
</ol>
<blockquote>
<p>kafka-console-producer.bat –broker-list localhost:9092 –topic demo</p>
</blockquote>
<h4 id="2-2-5-创建消费者"><a href="#2-2-5-创建消费者" class="headerlink" title="2.2.5 创建消费者"></a>2.2.5 创建消费者</h4><ol>
<li>在S:\devTools\kafka_2.11-0.10.0.0\bin\windows打开新的命令行。</li>
<li>输入下面的命令,回车:</li>
</ol>
<blockquote>
<p>kafka-console-consumer.bat –zookeeper localhost:2181 –topic demo</p>
</blockquote>
<h4 id="2-2-6-演示"><a href="#2-2-6-演示" class="headerlink" title="2.2.6 演示"></a>2.2.6 演示</h4><p>执行以上的命令之后有两个窗口:一个生产者,一个消费者。<br><img src="http://i.imgur.com/jtleTlg.png" alt=""><br>在producer命令行中任意输入内容,回车;在其他consumer命令行中能看到相应消息。如果能够将消息推送到consumer端并显示出来的话,Kafka安装就完成了。</p>
<p>最后上个成功的截图:</p>
<p><img src="http://i.imgur.com/cc10oms.png" alt=""></p>
<h3 id="2-3-常用的命令"><a href="#2-3-常用的命令" class="headerlink" title="2.3 常用的命令"></a>2.3 常用的命令</h3><ol>
<li>列出主题:kafka-topics.bat –-list –-zookeeper localhost:2181</li>
<li>描述主题:kafka-topics.bat –-describe –-zookeeper localhost:2181 –-topic [Topic Name]</li>
<li>从头读取消息:kafka-console-consumer.bat –-zookeeper localhost:2181 –-topic [Topic Name] –-from –beginning</li>
<li>删除主题:kafka-run-class.bat kafka.admin.TopicCommand –-delete –-topic [topic_to_delete] –-zookeeper localhost:2181</li>
<li>演示一个删除的:</li>
</ol>
<p><img src="http://i.imgur.com/FpHhmUb.png" alt=""></p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;前言&quot;&gt;&lt;a href=&quot;#前言&quot; class=&quot;headerlink&quot; title=&quot;前言&quot;&gt;&lt;/a&gt;前言&lt;/h2&gt;&lt;p&gt;由于项目涉及到kafka,自己以前没有接触过这方面的,学习了下,将搭建kafka运行环境同大家分享(单机搭建的Windows下的运行环境,Linux下的由于懒得装虚拟机就没有搭建,以后有时间在分享一次,搭建这个环境就是只为了学习)。&lt;/p&gt;
&lt;h2 id=&quot;1、基本概念&quot;&gt;&lt;a href=&quot;#1、基本概念&quot; class=&quot;headerlink&quot; title=&quot;1、基本概念&quot;&gt;&lt;/a&gt;1、基本概念&lt;/h2&gt;&lt;h3 id=&quot;1-1-什么是kafka&quot;&gt;&lt;a href=&quot;#1-1-什么是kafka&quot; class=&quot;headerlink&quot; title=&quot;1.1 什么是kafka&quot;&gt;&lt;/a&gt;1.1 什么是kafka&lt;/h3&gt;&lt;blockquote&gt;
&lt;p&gt;Apache Kafka is publish-subscribe messaging rethought as a distributed commit log。Kafka is a distributed, partitioned, replicated commit log service. It provides the functionality of a messaging system, but with a unique design.//官方解释&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Kafka是一种高吞吐量的分布式发布订阅消息系统,它提供了类似于JMS的特性,但是在设计实现上完全不同,此外它并不是JMS规范的实现。kafka对消息保存时根据Topic进行归类,发送消息者成为Producer,消息接受者成为Consumer,此外kafka集群有多个kafka实例组成,每个实例(server)成为broker。无论是kafka集群,还是producer和consumer都依赖于zookeeper来保证系统可用性集群保存一些meta信息。&lt;br&gt;整体运行机制如下图:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/LmF8AIe.png&quot; alt=&quot;&quot;&gt; &lt;/p&gt;
&lt;p&gt;图来源于官网&lt;/p&gt;
&lt;p&gt;更多内容请参看:&lt;a href=&quot;http://kafka.apache.org/documentation.html&quot;&gt;官方文档&lt;/a&gt;,这里就不一一翻译了。&lt;br&gt;
</summary>
<category term="kafka" scheme="http://zhengweishan.oschina.io/categories/kafka/"/>
<category term="kafka" scheme="http://zhengweishan.oschina.io/tags/kafka/"/>
</entry>
<entry>
<title>JMS学习(四)-----Spring和ActiveMQ整合的完整实例</title>
<link href="http://zhengweishan.oschina.io/2017/01/25/JMS%E5%AD%A6%E4%B9%A0%EF%BC%88%E5%9B%9B%EF%BC%89Spring%E5%92%8CActiveMQ%E6%95%B4%E5%90%88%E7%9A%84%E5%AE%8C%E6%95%B4%E5%AE%9E%E4%BE%8B/"/>
<id>http://zhengweishan.oschina.io/2017/01/25/JMS学习(四)Spring和ActiveMQ整合的完整实例/</id>
<published>2017-01-24T16:00:00.000Z</published>
<updated>2017-03-01T08:40:05.554Z</updated>
<content type="html"><![CDATA[<h2 id="1、前言"><a href="#1、前言" class="headerlink" title="1、前言"></a>1、前言</h2><p>我们基于Spring+JMS+ActiveMQ+Tomcat,做一个Spring4.2.6和ActiveMQ5.7.0整合实例,实现了Point-To-Point的异步队列消息和PUB/SUB(发布/订阅)模型,简单实例,不包含任何业务。</p>
<h2 id="项目结构"><a href="#项目结构" class="headerlink" title="项目结构"></a>项目结构</h2><p><img src="http://i.imgur.com/EGswcsP.png" alt=""></p>
<a id="more"></a>
<h2 id="2、配置文件"><a href="#2、配置文件" class="headerlink" title="2、配置文件"></a>2、配置文件</h2><h3 id="2-1-pom-xml"><a href="#2-1-pom-xml" class="headerlink" title="2.1 pom.xml"></a>2.1 pom.xml</h3><pre><code>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;groupId&gt;com.activemq.demo&lt;/groupId&gt;
&lt;artifactId&gt;SpringActiveMq&lt;/artifactId&gt;
&lt;packaging&gt;war&lt;/packaging&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;SpringActiveMq Maven Webapp&lt;/name&gt;
&lt;url&gt;http://maven.apache.org&lt;/url&gt;
&lt;properties&gt;
&lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
&lt;org.springframework.version&gt;4.2.6.RELEASE&lt;/org.springframework.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;junit&lt;/groupId&gt;
&lt;artifactId&gt;junit&lt;/artifactId&gt;
&lt;version&gt;3.8.1&lt;/version&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.servlet&lt;/groupId&gt;
&lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
&lt;version&gt;3.1.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-context&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-context-support&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-web&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- activeMQ与spring整合所需要的包 --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework&lt;/groupId&gt;
&lt;artifactId&gt;spring-jms&lt;/artifactId&gt;
&lt;version&gt;${org.springframework.version}&lt;/version&gt;
&lt;/dependency&gt;
&lt;!-- activeMQ --&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.activemq&lt;/groupId&gt;
&lt;artifactId&gt;activemq-core&lt;/artifactId&gt;
&lt;version&gt;5.7.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.apache.xbean&lt;/groupId&gt;
&lt;artifactId&gt;xbean-spring&lt;/artifactId&gt;
&lt;version&gt;4.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
&lt;artifactId&gt;jackson-core-asl&lt;/artifactId&gt;
&lt;version&gt;1.9.12&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
&lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt;
&lt;version&gt;1.9.12&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;net.sf.json-lib&lt;/groupId&gt;
&lt;artifactId&gt;json-lib&lt;/artifactId&gt;
&lt;version&gt;2.4&lt;/version&gt;
&lt;classifier&gt;jdk15&lt;/classifier&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-core&lt;/artifactId&gt;
&lt;version&gt;2.4.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
&lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
&lt;version&gt;2.4.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;finalName&gt;SpringActiveMq&lt;/finalName&gt;
&lt;/build&gt;
&lt;/project&gt;
</code></pre><h3 id="2-2-spring-activeMQ-xml"><a href="#2-2-spring-activeMQ-xml" class="headerlink" title="2.2 spring-activeMQ.xml"></a>2.2 spring-activeMQ.xml</h3><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:amq=&quot;http://activemq.apache.org/schema/core&quot;
xmlns:jms=&quot;http://www.springframework.org/schema/jms&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.7.0.xsd&quot;&gt;
&lt;!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 --&gt;
&lt;bean id=&quot;targetConnectionFactory&quot; class=&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;&gt;
&lt;property name=&quot;brokerURL&quot; value=&quot;tcp://localhost:61616&quot; /&gt;
&lt;/bean&gt;
&lt;!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory --&gt;
&lt;bean id=&quot;connectionFactory&quot; class=&quot;org.springframework.jms.connection.CachingConnectionFactory&quot;&gt;
&lt;!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的pooledConnectionFactory --&gt;
&lt;property name=&quot;targetConnectionFactory&quot; ref=&quot;targetConnectionFactory&quot; /&gt;
&lt;property name=&quot;sessionCacheSize&quot; value=&quot;100&quot; /&gt;
&lt;/bean&gt;
&lt;!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 --&gt;
&lt;bean id=&quot;jmsTemplate&quot; class=&quot;org.springframework.jms.core.JmsTemplate&quot;&gt;
&lt;!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 --&gt;
&lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; /&gt;
&lt;!-- 非pub/sub模型(发布/订阅),即队列模式 --&gt;
&lt;property name=&quot;pubSubDomain&quot; value=&quot;false&quot; /&gt;
&lt;/bean&gt;
&lt;!--这个是队列目的地,点对点的 --&gt;
&lt;bean id=&quot;queueDestination&quot; class=&quot;org.apache.activemq.command.ActiveMQQueue&quot;&gt;
&lt;constructor-arg&gt;
&lt;value&gt;queue&lt;/value&gt;
&lt;/constructor-arg&gt;
&lt;/bean&gt;
&lt;!--这个是主题目的地,一对多的 --&gt;
&lt;bean id=&quot;topicDestination&quot; class=&quot;org.apache.activemq.command.ActiveMQTopic&quot;&gt;
&lt;constructor-arg value=&quot;topic&quot; /&gt;
&lt;/bean&gt;
&lt;!-- 消息监听器 --&gt;
&lt;bean id=&quot;consumerMessageListener&quot; class=&quot;com.activemq.demo.ConsumerMessageListener&quot; /&gt;
&lt;!-- 消息监听容器 --&gt;
&lt;bean id=&quot;jmsContainer&quot;
class=&quot;org.springframework.jms.listener.DefaultMessageListenerContainer&quot;&gt;
&lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; /&gt;
&lt;property name=&quot;destination&quot; ref=&quot;queueDestination&quot; /&gt;
&lt;property name=&quot;messageListener&quot; ref=&quot;consumerMessageListener&quot; /&gt;
&lt;/bean&gt;
&lt;/beans&gt;
</code></pre><h3 id="2-3-servlet-context-xml"><a href="#2-3-servlet-context-xml" class="headerlink" title="2.3 servlet-context.xml"></a>2.3 servlet-context.xml</h3><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
xmlns:mvc=&quot;http://www.springframework.org/schema/mvc&quot;
xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd&quot;
default-lazy-init=&quot;false&quot;&gt;
&lt;mvc:annotation-driven &gt;
&lt;!-- 消息转换器 --&gt;
&lt;mvc:message-converters register-defaults=&quot;true&quot;&gt;
&lt;bean class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;
&lt;property name=&quot;supportedMediaTypes&quot; value=&quot;text/html;charset=UTF-8&quot;/&gt;
&lt;/bean&gt;
&lt;bean class=&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;&gt;
&lt;property name=&quot;supportedMediaTypes&quot;&gt;
&lt;list&gt;
&lt;value&gt;text/html; charset=UTF-8&lt;/value&gt;
&lt;value&gt;application/json;charset=UTF-8&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;/mvc:message-converters&gt;
&lt;/mvc:annotation-driven&gt;
&lt;!-- 静态资源 --&gt;
&lt;mvc:resources mapping=&quot;/resources/**&quot; location=&quot;/resources/&quot;/&gt;
&lt;!-- 中文乱码解决 --&gt;
&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot; &gt;
&lt;property name=&quot;messageConverters&quot;&gt;
&lt;list&gt;
&lt;bean class = &quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;
&lt;property name = &quot;supportedMediaTypes&quot;&gt;
&lt;list&gt;
&lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;context:component-scan base-package=&quot;com.activemq.demo&quot;/&gt;
&lt;/beans&gt;
</code></pre><h3 id="2-4-web-xml"><a href="#2-4-web-xml" class="headerlink" title="2.4 web.xml"></a>2.4 web.xml</h3><pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE web-app PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot; &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;&gt;
&lt;web-app&gt;
&lt;display-name&gt;dubbo_consumer&lt;/display-name&gt;
&lt;description&gt;dubbo_consumer test&lt;/description&gt;
&lt;context-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;
classpath*:spring-activeMQ.xml
&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;listener&gt;
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
&lt;servlet&gt;
&lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
&lt;param-value&gt;classpath*:servlet-context.xml&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;/web-app&gt;
</code></pre><h2 id="3、部署运行"><a href="#3、部署运行" class="headerlink" title="3、部署运行"></a>3、部署运行</h2><p>部署之后访问:<a href="http://localhost:8081/SpringActiveMq/test/sendMessage,效果如下:" target="_blank" rel="external">http://localhost:8081/SpringActiveMq/test/sendMessage,效果如下:</a></p>
<p><img src="http://i.imgur.com/8lPxbUB.png" alt=""></p>
<p>ActiveMq控制台:</p>
<p><img src="http://i.imgur.com/gqBbYAH.png" alt=""></p>
<h2 id="4、spring-activeMQ-xml解析"><a href="#4、spring-activeMQ-xml解析" class="headerlink" title="4、spring-activeMQ.xml解析"></a>4、spring-activeMQ.xml解析</h2><h4 id="4-1-配置ConnectionFactory"><a href="#4-1-配置ConnectionFactory" class="headerlink" title="4.1 配置ConnectionFactory"></a>4.1 配置ConnectionFactory</h4><p>connectionFactory是Spring用于创建到JMS服务器链接的,Spring提供了多种connectionFactory,我们介绍两个SingleConnectionFactory和CachingConnectionFactory。</p>
<ol>
<li><p>SingleConnectionFactory:对于建立JMS服务器链接的请求会一直返回同一个链接,并且会忽略Connection的close方法调用。</p>
</li>
<li><p>CachingConnectionFactory:继承了SingleConnectionFactory,所以它拥有SingleConnectionFactory的所有功能,同时它还新增了缓存功能,它可以缓存Session、MessageProducer和MessageConsumer。我们使用CachingConnectionFactory来作为示例。</p>
</li>
</ol>
<p>Spring提供的ConnectionFactory只是Spring用于管理ConnectionFactory的,真正产生到JMS服务器链接的ConnectionFactory还得是由JMS服务厂商提供,并且需要把它注入到Spring提供的ConnectionFactory中。我们这里使用的是ActiveMQ实现的JMS,所以在我们这里真正的可以产生Connection的就应该是由ActiveMQ提供的ConnectionFactory。所以定义一个ConnectionFactory的完整代码应该如下所示:</p>
<pre><code> &lt;!-- 连接池 --&gt;
&lt;bean id=&quot;pooledConnectionFactory&quot; class=&quot;org.apache.activemq.pool.PooledConnectionFactory&quot; destroy-method=&quot;stop&quot;&gt;
&lt;property name=&quot;connectionFactory&quot;&gt;
&lt;bean class=&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;&gt;
&lt;property name=&quot;brokerURL&quot; value=&quot;tcp://localhost:61616&quot; /&gt;
&lt;/bean&gt;
&lt;/property&gt;
&lt;/bean&gt;
&lt;!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 --&gt;
&lt;!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616--&gt;
&lt;bean id=&quot;targetConnectionFactory&quot; class=&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;&gt;
&lt;property name=&quot;brokerURL&quot; value=&quot;tcp://localhost:61616&quot; /&gt;
&lt;/bean&gt;
&lt;!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory --&gt;
&lt;bean id=&quot;connectionFactory&quot; class=&quot;org.springframework.jms.connection.CachingConnectionFactory&quot;&gt;
&lt;!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的pooledConnectionFactory --&gt;
&lt;property name=&quot;targetConnectionFactory&quot; ref=&quot;targetConnectionFactory&quot; /&gt;
&lt;property name=&quot;sessionCacheSize&quot; value=&quot;100&quot; /&gt;
&lt;/bean&gt;
</code></pre><p>或者这样配置:</p>
<pre><code> &lt;!-- ActiveMQ 连接工厂 --&gt;
&lt;!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供--&gt;
&lt;!-- 如果连接网络:tcp://ip:61616;未连接网络:tcp://localhost:61616 以及用户名,密码--&gt;
&lt;amq:connectionFactory id=&quot;amqConnectionFactory&quot;
brokerURL=&quot;tcp://192.168.3.3:61616&quot; userName=&quot;admin&quot; password=&quot;admin&quot; /&gt;
&lt;!-- Spring Caching连接工厂 --&gt;
&lt;!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory --&gt;
&lt;bean id=&quot;connectionFactory&quot; class=&quot;org.springframework.jms.connection.CachingConnectionFactory&quot;&gt;
&lt;!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory --&gt;
&lt;property name=&quot;targetConnectionFactory&quot; ref=&quot;amqConnectionFactory&quot;&gt;&lt;/property&gt;
&lt;!-- 同上,同理 --&gt;
&lt;!-- &lt;constructor-arg ref=&quot;amqConnectionFactory&quot; /&gt; --&gt;
&lt;!-- Session缓存数量 --&gt;
&lt;property name=&quot;sessionCacheSize&quot; value=&quot;100&quot; /&gt;
&lt;/bean&gt;
</code></pre><h4 id="4-2-配置生产者"><a href="#4-2-配置生产者" class="headerlink" title="4.2 配置生产者"></a>4.2 配置生产者</h4><p>配置好ConnectionFactory之后我们就需要配置生产者。生产者负责产生消息并发送到JMS服务器。但是我们要怎么进行消息发送呢?通常是利用Spring为我们提供的JmsTemplate类来实现的,所以配置生产者其实最核心的就是配置消息发送的JmsTemplate。对于消息发送者而言,它在发送消息的时候要知道自己该往哪里发,为此,我们在定义JmsTemplate的时候需要注入一个Spring提供的ConnectionFactory对象。</p>
<p>在利用JmsTemplate进行消息发送的时候,我们需要知道发送哪种消息类型:一个是点对点的ActiveMQQueue,另一个就是支持订阅/发布模式的ActiveMQTopic。如下所示:</p>
<pre><code>&lt;!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 --&gt;
&lt;bean id=&quot;jmsTemplate&quot; class=&quot;org.springframework.jms.core.JmsTemplate&quot;&gt;
&lt;!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 --&gt;
&lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; /&gt;
&lt;!-- 非pub/sub模型(发布/订阅),即队列模式 如果value是true pub/sub模型(发布/订阅) --&gt;
&lt;property name=&quot;pubSubDomain&quot; value=&quot;false&quot; /&gt;
&lt;/bean&gt;
</code></pre><h4 id="4-3-配置消费者"><a href="#4-3-配置消费者" class="headerlink" title="4.3 配置消费者"></a>4.3 配置消费者</h4><p>生产者往指定目的地Destination发送消息后,接下来就是消费者对指定目的地的消息进行消费了。那么消费者是如何知道有生产者发送消息到指定目的地Destination了呢?每个消费者对应每个目的地都需要有对应的MessageListenerContainer。对于消息监听容器而言,除了要知道监听哪个目的地之外,还需要知道到哪里去监听,也就是说它还需要知道去监听哪个JMS服务器,通过配置MessageListenerContainer的时候往里面注入一个ConnectionFactory来实现的。所以我们在配置一个MessageListenerContainer的时候有三个属性必须指定:一个是表示从哪里监听的ConnectionFactory;一个是表示监听什么的Destination;一个是接收到消息以后进行消息处理的MessageListener。</p>
<pre><code>&lt;!-- 消息监听器 --&gt;
&lt;bean id=&quot;consumerMessageListener&quot; class=&quot;com.activemq.demo.ConsumerMessageListener&quot; /&gt;
&lt;!-- 消息监听容器 --&gt;
&lt;bean id=&quot;jmsContainer&quot;
class=&quot;org.springframework.jms.listener.DefaultMessageListenerContainer&quot;&gt;
&lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot; /&gt;
&lt;property name=&quot;destination&quot; ref=&quot;queueDestination&quot; /&gt;
&lt;property name=&quot;messageListener&quot; ref=&quot;consumerMessageListener&quot; /&gt;
&lt;/bean&gt;
</code></pre><h2 id="5、总结"><a href="#5、总结" class="headerlink" title="5、总结"></a>5、总结</h2><p>Spring提供了对JMS的支持,ActiveMQ提供了很好的实现,而此时我们已经将两者完美的结合在了一起。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、前言&quot;&gt;&lt;a href=&quot;#1、前言&quot; class=&quot;headerlink&quot; title=&quot;1、前言&quot;&gt;&lt;/a&gt;1、前言&lt;/h2&gt;&lt;p&gt;我们基于Spring+JMS+ActiveMQ+Tomcat,做一个Spring4.2.6和ActiveMQ5.7.0整合实例,实现了Point-To-Point的异步队列消息和PUB/SUB(发布/订阅)模型,简单实例,不包含任何业务。&lt;/p&gt;
&lt;h2 id=&quot;项目结构&quot;&gt;&lt;a href=&quot;#项目结构&quot; class=&quot;headerlink&quot; title=&quot;项目结构&quot;&gt;&lt;/a&gt;项目结构&lt;/h2&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/EGswcsP.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
</summary>
<category term="JMS" scheme="http://zhengweishan.oschina.io/categories/JMS/"/>
<category term="JMS" scheme="http://zhengweishan.oschina.io/tags/JMS/"/>
<category term="ActiveMQ" scheme="http://zhengweishan.oschina.io/tags/ActiveMQ/"/>
</entry>
<entry>
<title>JMS学习(三)----- ActiveMQ简单的HelloWorld实例</title>
<link href="http://zhengweishan.oschina.io/2017/01/24/JMS%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%89%EF%BC%89ActiveMQ%E7%AE%80%E5%8D%95%E7%9A%84HelloWorld%E5%AE%9E%E4%BE%8B/"/>
<id>http://zhengweishan.oschina.io/2017/01/24/JMS学习(三)ActiveMQ简单的HelloWorld实例/</id>
<published>2017-01-23T16:00:00.000Z</published>
<updated>2017-03-01T08:40:01.239Z</updated>
<content type="html"><![CDATA[<h2 id="开发环境"><a href="#开发环境" class="headerlink" title="开发环境"></a>开发环境</h2><p>我使用的是ActiveMQ 5.13.3 Release的Windows版,官网最新版是ActiveMQ 5.13.4 Release,大家可以自行下载,<a href="http://activemq.apache.org/download-archives.html" target="_blank" rel="external">下载地址</a>。</p>
<p>需要注意的是,开发时候,要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面,这个包包含了所有jms接口api的实现。</p>
<p>项目截图:</p>
<p><img src="http://i.imgur.com/pPp8eMU.png" alt=""></p>
<h2 id="ActiviteMQ消息有3中形式"><a href="#ActiviteMQ消息有3中形式" class="headerlink" title="ActiviteMQ消息有3中形式"></a>ActiviteMQ消息有3中形式</h2><p><strong>JMS 公共 ———-点对点域 ———-发布/订阅域</strong></p>
<p>ConnectionFactory ———- QueueConnectionFactory ———- TopicConnectionFactory</p>
<p>Connection ———- QueueConnection ———- TopicConnection</p>
<p>Destination ———- Queue ———- Topic</p>
<p>Session ———- QueueSession ———- TopicSession</p>
<p>MessageProducer ———- QueueSender ———- TopicPublisher</p>
<p>MessageConsumer ———- QueueReceiver ———- TopicSubscriber</p>
<p>(1)、点对点方式(point-to-point)</p>
<p>点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存贮消息,Sneder 发送消息,receive接收消息.具体点就是Sender Client发送Message Queue ,而 receiver Cliernt从Queue中接收消息和”发送消息已接受”到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行</p>
<p>(2)、发布/订阅 方式(publish/subscriber Messaging)</p>
<p>发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber ,在接收消息时有两种方法,destination的receive方法,和实现message listener 接口的onMessage 方法。</p>
<a id="more"></a>
<h2 id="ActiviteMQ接收和发送消息基本流程"><a href="#ActiviteMQ接收和发送消息基本流程" class="headerlink" title="ActiviteMQ接收和发送消息基本流程"></a>ActiviteMQ接收和发送消息基本流程</h2><p><img src="http://i.imgur.com/g71ThMY.png" alt=""></p>
<p><strong>发送消息的基本步骤:</strong></p>
<p>(1)、创建连接使用的工厂类JMS ConnectionFactory</p>
<p>(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动</p>
<p>(3)、使用连接Connection 建立会话Session</p>
<p>(4)、使用会话Session和管理对象Destination创建消息生产者MessageSender</p>
<p>(5)、使用消息生产者MessageSender发送消息</p>
<p><strong>消息接收者从JMS接受消息的步骤</strong></p>
<p>(1)、创建连接使用的工厂类JMS ConnectionFactory</p>
<p>(2)、使用管理对象JMS ConnectionFactory建立连接Connection,并启动</p>
<p>(3)、使用连接Connection 建立会话Session</p>
<p>(4)、使用会话Session和管理对象Destination创建消息接收者MessageReceiver</p>
<p>(5)、使用消息接收者MessageReceiver接受消息,需要用setMessageListener将MessageListener接口绑定到MessageReceiver消息接收者必须实现了MessageListener接口,需要定义onMessage事件方法。</p>
<h3 id="使用JMS方式发送接收消息"><a href="#使用JMS方式发送接收消息" class="headerlink" title="使用JMS方式发送接收消息"></a>使用JMS方式发送接收消息</h3><pre><code>package com.active.mq.demo;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
public class MQConnectionFactory {
private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认连接用户名
private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码
private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;//默认连接地址
private static ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);//连接工厂
/**
* 通过连接工厂获取连接
* @return
*/
public static Connection getConnection(){
Connection connection = null;
try {
connection = connectionFactory.createConnection();
} catch (JMSException e) {
e.printStackTrace();
}
return connection;
}
}
package com.active.mq.demo;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
public class JMSConsumer {
public static void main(String[] args) {
Connection connection = null;//连接
Session session = null;//会话 接受或者发送消息的线程
Destination destination;//消息的目的地
MessageConsumer messageConsumer;//消息的消费者
try {
//通过连接工厂获取连接
connection = MQConnectionFactory.getConnection();
//启动连接
connection.start();
//创建session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建一个连接HelloWorld的消息队列
destination = session.createQueue(&quot;HelloWorld&quot;);
//创建消息消费者
messageConsumer = session.createConsumer(destination);
while (true) {
TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
if(textMessage != null){
System.out.println(&quot;收到的消息:&quot; + textMessage.getText());
}else {
break;
}
}
//提交回话
session.commit();
} catch (JMSException e) {
e.printStackTrace();
}finally{
if(connection != null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(session !=null){
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
package com.active.mq.demo;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
public class JMSProducer {
//发送的消息数量
private static final int SENDNUM = 10;
public static void main(String[] args) {
//连接
Connection connection = null;
//会话 接受或者发送消息的线程
Session session = null;
//消息的目的地
Destination destination;
//消息生产者
MessageProducer messageProducer;
try {
//通过连接工厂获取连接
connection = MQConnectionFactory.getConnection();
//启动连接
connection.start();
//创建session
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
//创建一个名称为HelloWorld的消息队列
destination = session.createQueue(&quot;HelloWorld&quot;);
//创建消息生产者
messageProducer = session.createProducer(destination);
//发送消息
sendMessage(session, messageProducer);
//提交回话
session.commit();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(connection != null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(session !=null){
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
/**
* 发送消息
* @param session
* @param messageProducer 消息生产者
* @throws Exception
*/
public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{
for (int i = 0; i &lt; JMSProducer.SENDNUM; i++) {
//创建一条文本消息
TextMessage message = session.createTextMessage(&quot;发送JMS消息第&quot; + (i + 1) + &quot;条&quot;);
System.out.println(&quot;发送消息:Activemq 发送JMS消息&quot; + (i + 1));
//通过消息生产者发出消息
messageProducer.send(message);
}
}
}
</code></pre><h3 id="Queue队列方式发送点对点消息数据"><a href="#Queue队列方式发送点对点消息数据" class="headerlink" title="Queue队列方式发送点对点消息数据"></a>Queue队列方式发送点对点消息数据</h3><p>在获取工厂类中加入如下代码:</p>
<pre><code>private static QueueConnectionFactory queueConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
/**
* 通过连接工厂获取连接(Queue方式)
* @return
*/
public static QueueConnection getQueueConnection(){
QueueConnection connection = null;
try {
connection = queueConnectionFactory.createQueueConnection();
} catch (JMSException e) {
e.printStackTrace();
}
return connection;
}
//消息生产者
package com.active.mq.demo;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
public class QueueProducer {
private static final int SEND_NUM = 10;
public static void main(String[] args) {
QueueConnection queueConnection = null;
QueueSession queueSession = null;
try {
// 通过工厂创建一个连接
queueConnection = MQConnectionFactory.getQueueConnection();
// 启动连接
queueConnection.start();
// 创建一个session会话
queueSession = queueConnection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
Queue queue = queueSession.createQueue(&quot;QueueMsgDemo&quot;);
// 创建消息发送者
QueueSender sender = queueSession.createSender(queue);
// 设置持久化模式
sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMessage(queueSession, sender);
// 提交会话
queueSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
// 关闭释放资源
if (queueSession != null) {
try {
queueSession.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
public static void sendMessage(QueueSession session, QueueSender sender) throws Exception {
for (int i = 0; i &lt; SEND_NUM; i++) {
String message = &quot;发送queue消息第&quot; + (i + 1) + &quot;条&quot;;
//创建一个Map集合信息
MapMessage map = session.createMapMessage();
map.setString(&quot;text&quot;, message);
map.setLong(&quot;time&quot;, System.currentTimeMillis());
System.out.println(&quot;ActiveMQ 发送queue消息:&quot;+(i + 1));
sender.send(map);
}
}
}
//消费者
package com.active.mq.demo;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
public class QueueConsumer {
public static void main(String[] args) {
QueueConnection queueConnection = null;
QueueSession queueSession = null;
try {
// 通过工厂创建一个连接
queueConnection = MQConnectionFactory.getQueueConnection();
// 启动连接
queueConnection.start();
// 创建一个session会话
queueSession = queueConnection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
Queue queue = queueSession.createQueue(&quot;QueueMsgDemo&quot;);
// 创建消息接收者
QueueReceiver receiver = queueSession.createReceiver(queue);
receiver.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
if (msg != null) {
MapMessage map = (MapMessage) msg;
try {
System.out.println(map.getLong(&quot;time&quot;) + &quot;接收到消息#&quot; + map.getString(&quot;text&quot;));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
// 休眠100ms再关闭
Thread.sleep(1000 * 100);
// 提交会话
queueSession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭释放资源
if (queueSession != null) {
try {
queueSession.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
</code></pre><h3 id="Topic主题发布和订阅消息"><a href="#Topic主题发布和订阅消息" class="headerlink" title="Topic主题发布和订阅消息"></a>Topic主题发布和订阅消息</h3><p>在获取工厂类中加入如下代码:</p>
<pre><code> private static TopicConnectionFactory topicConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
/**
* 通过连接工厂获取连接(Topic方式)
* @return
*/
public static TopicConnection getTopicConnection(){
TopicConnection topicConnection = null;
try {
topicConnection = topicConnectionFactory.createTopicConnection();
} catch (JMSException e) {
e.printStackTrace();
}
return topicConnection;
}
//生产者
package com.active.mq.demo;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
public class TopicProducer {
private static final int SEND_NUM = 10;
public static void main(String[] args) {
TopicConnection connection = null;
TopicSession session = null;
try {
// 通过工厂创建一个连接
connection = MQConnectionFactory.getTopicConnection();
// 启动连接
connection.start();
// 创建一个session会话
session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
Topic topic = session.createTopic(&quot;TopicDemo&quot;);
// 创建消息发送者
TopicPublisher publisher = session.createPublisher(topic);
// 设置持久化模式
publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMessage(session, publisher);
// 提交会话
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭释放资源
if (session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
public static void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception {
for (int i = 0; i &lt; SEND_NUM; i++) {
String message = &quot;发送Topic消息第&quot; + (i + 1) + &quot;条&quot;;
MapMessage map = session.createMapMessage();
map.setString(&quot;text&quot;, message);
map.setLong(&quot;time&quot;, System.currentTimeMillis());
System.out.println(&quot;ActiveMQ 发送Topic消息:&quot;+(i + 1));
publisher.send(map);
}
}
}
//消费者
package com.active.mq.demo;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
public class TopicConsumer {
public static void main(String[] args) {
TopicConnection connection = null;
TopicSession session = null;
try {
// 通过工厂创建一个连接
connection = MQConnectionFactory.getTopicConnection();
// 启动连接
connection.start();
// 创建一个session会话
session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
// 创建一个消息队列
Topic topic = session.createTopic(&quot;TopicDemo&quot;);
// 创建消息消费者
TopicSubscriber subscriber = session.createSubscriber(topic);
subscriber.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
if (msg != null) {
MapMessage map = (MapMessage) msg;
try {
System.out.println(map.getLong(&quot;time&quot;) + &quot;Topic接收消息#&quot; + map.getString(&quot;text&quot;));
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
// 休眠100ms再关闭
Thread.sleep(1000 * 100);
// 提交会话
session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭释放资源
if (session != null) {
try {
session.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
}
</code></pre><h2 id="运行"><a href="#运行" class="headerlink" title="运行"></a>运行</h2><p>以使用JMS方式发送接收消息为例说明<br>1、首先,启动ActiveMQ<br>2、运行发送者,eclipse控制台输出,如下图:</p>
<p><img src="http://i.imgur.com/pxZmjXj.png" alt=""><br>3、查看ActiveMQ服务器,Queues内容如下:</p>
<p><img src="http://i.imgur.com/a7R59y3.png" alt=""></p>
<p>我们可以看到创建了一个名称为HelloWorld的消息队列,队列中有10条消息未被消费,我们也可以通过Browse查看是哪些消息,如果这些队列中的消息,被删除,消费者则无法消费。</p>
<p><img src="http://i.imgur.com/AQpd48x.png" alt=""></p>
<p>4、运行一下消费者,eclipse控制台打印消息,如下:</p>
<p><img src="http://i.imgur.com/T66lsxc.png" alt=""></p>
<p>5、我们在查看一下ActiveMQ服务器,Queues内容如下:</p>
<p><img src="http://i.imgur.com/l63Vrxg.png" alt=""></p>
<p>我们可以看到HelloWorld的消息队列发生变化,多一个消息者,队列中的10条消息被消费了,点击Browse查看,已经为空了。<br>点击Active Consumers,我们可以看到这个消费者的详细信息。</p>
<p><img src="http://i.imgur.com/44UYCg0.png" alt=""></p>
<p>实例到此就结束了,大家可以自己多看点ActiveMQ服务器的内容,进一步熟悉ActiveMQ。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;开发环境&quot;&gt;&lt;a href=&quot;#开发环境&quot; class=&quot;headerlink&quot; title=&quot;开发环境&quot;&gt;&lt;/a&gt;开发环境&lt;/h2&gt;&lt;p&gt;我使用的是ActiveMQ 5.13.3 Release的Windows版,官网最新版是ActiveMQ 5.13.4 Release,大家可以自行下载,&lt;a href=&quot;http://activemq.apache.org/download-archives.html&quot;&gt;下载地址&lt;/a&gt;。&lt;/p&gt;
&lt;p&gt;需要注意的是,开发时候,要将apache-activemq-5.13.3-bin.zip解压缩后里面的activemq-all-5.13.3.jar包加入到classpath下面,这个包包含了所有jms接口api的实现。&lt;/p&gt;
&lt;p&gt;项目截图:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/pPp8eMU.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;ActiviteMQ消息有3中形式&quot;&gt;&lt;a href=&quot;#ActiviteMQ消息有3中形式&quot; class=&quot;headerlink&quot; title=&quot;ActiviteMQ消息有3中形式&quot;&gt;&lt;/a&gt;ActiviteMQ消息有3中形式&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;JMS 公共 ———-点对点域 ———-发布/订阅域&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;ConnectionFactory ———- QueueConnectionFactory ———- TopicConnectionFactory&lt;/p&gt;
&lt;p&gt;Connection ———- QueueConnection ———- TopicConnection&lt;/p&gt;
&lt;p&gt;Destination ———- Queue ———- Topic&lt;/p&gt;
&lt;p&gt;Session ———- QueueSession ———- TopicSession&lt;/p&gt;
&lt;p&gt;MessageProducer ———- QueueSender ———- TopicPublisher&lt;/p&gt;
&lt;p&gt;MessageConsumer ———- QueueReceiver ———- TopicSubscriber&lt;/p&gt;
&lt;p&gt;(1)、点对点方式(point-to-point)&lt;/p&gt;
&lt;p&gt;点对点的消息发送方式主要建立在 Message Queue,Sender,reciever上,Message Queue 存贮消息,Sneder 发送消息,receive接收消息.具体点就是Sender Client发送Message Queue ,而 receiver Cliernt从Queue中接收消息和”发送消息已接受”到Quere,确认消息接收。消息发送客户端与接收客户端没有时间上的依赖,发送客户端可以在任何时刻发送信息到Queue,而不需要知道接收客户端是不是在运行&lt;/p&gt;
&lt;p&gt;(2)、发布/订阅 方式(publish/subscriber Messaging)&lt;/p&gt;
&lt;p&gt;发布/订阅方式用于多接收客户端的方式.作为发布订阅的方式,可能存在多个接收客户端,并且接收端客户端与发送客户端存在时间上的依赖。一个接收端只能接收他创建以后发送客户端发送的信息。作为subscriber ,在接收消息时有两种方法,destination的receive方法,和实现message listener 接口的onMessage 方法。&lt;/p&gt;
</summary>
<category term="JMS" scheme="http://zhengweishan.oschina.io/categories/JMS/"/>
<category term="JMS" scheme="http://zhengweishan.oschina.io/tags/JMS/"/>
<category term="ActiveMQ" scheme="http://zhengweishan.oschina.io/tags/ActiveMQ/"/>
</entry>
<entry>
<title>JMS学习(二)----- ActiveMQ简单介绍以及安装</title>
<link href="http://zhengweishan.oschina.io/2017/01/23/JMS%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%BA%8C%EF%BC%89ActiveMQ%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D%E4%BB%A5%E5%8F%8A%E5%AE%89%E8%A3%85/"/>
<id>http://zhengweishan.oschina.io/2017/01/23/JMS学习(二)ActiveMQ简单介绍以及安装/</id>
<published>2017-01-22T16:00:00.000Z</published>
<updated>2017-03-01T08:39:57.456Z</updated>
<content type="html"><![CDATA[<h2 id="1、简介"><a href="#1、简介" class="headerlink" title="1、简介"></a>1、简介</h2><p>ActiveMQ是一个易于使用的消息中间件(MOM:Message Orient middleware)。</p>
<p>消息中间件有很多的用途和优点: </p>
<ol>
<li>将数据从一个应用程序传送到另一个应用程序,或者从软件的一个模块传送到另外一个模块; </li>
<li>负责建立网络通信的通道,进行数据的可靠传送。 </li>
<li>保证数据不重发,不丢失 </li>
<li>能够实现跨平台操作,能够为不同操作系统上的软件集成技工数据传送服务</li>
</ol>
<p>首先我们先说下什么是MQ,MQ英文名MessageQueue,中文名也就是大家用的消息队列,干嘛用的呢,说白了就是一个消息的接受和转发的容器,可用于消息推送。下面介绍主题,就是ActiveMQ:</p>
<p>ActiveMQ是由Apache出品的,一款最流行的,能力强劲的开源消息总线。ActiveMQ是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,它非常快速,支持多种语言的客户端和协议,而且可以非常容易的嵌入到企业的应用环境中,并有许多高级功能。</p>
<a id="more"></a>
<h2 id="2、下载与配置"><a href="#2、下载与配置" class="headerlink" title="2、下载与配置"></a>2、下载与配置</h2><h3 id="2-1-下载"><a href="#2-1-下载" class="headerlink" title="2.1 下载"></a>2.1 下载</h3><p><a href="http://activemq.apache.org/download.html" target="_blank" rel="external">官网下载ActiveMQ</a> 现在ActiveMQ最新的版本是5.13.3。</p>
<h3 id="2-2-启动"><a href="#2-2-启动" class="headerlink" title="2.2 启动"></a>2.2 启动</h3><p>下载之后解压缩目录结构如图:</p>
<p><img src="http://i.imgur.com/i6foU0f.png" alt=""></p>
<p>从它的目录来说,还是很简单的: </p>
<ul>
<li>bin存放的是脚本文件</li>
<li>conf存放的是基本配置文件</li>
<li>data存放的是日志文件</li>
<li>docs存放的是说明文档</li>
<li>examples存放的是简单的实例</li>
<li>lib存放的是activemq所需jar包</li>
<li>webapps用于存放项目的目录</li>
</ul>
<p>启动ActiveMQ:<br>进去bin目录下你会发现下图这样的内容:</p>
<p><img src="http://i.imgur.com/zfysAGw.png" alt=""></p>
<p>win32文件夹是32位操作系统的启动命令,win64文件夹是64位操作系统的启动命令,文件内容都是如下:</p>
<p><img src="http://i.imgur.com/ICmekqG.png" alt=""></p>
<p>这样就会有三个activemq.bat脚本文件,如果直接启动bin目录下的这个脚本文件,直接闪退(这个问题一直不知道怎么回事,回头看看脚本执行文件),启动不了服务。如果根据自己的操作系统选择对应的执行脚本则可以启动成功,可以看到下图的效果。</p>
<p><img src="http://i.imgur.com/RxA5Ksa.png" alt=""></p>
<p>从上图我们可以看到activemq的存放地址,以及浏览器要访问的地址. </p>
<p>ActiveMQ默认使用的TCP连接端口是61616, 通过查看该端口的信息可以测试ActiveMQ是否成功启动 netstat -an|find “61616” 如图:</p>
<p><img src="http://i.imgur.com/XPNcEm6.png" alt=""></p>
<p>ActiveMQ默认启动时,启动了内置的jetty服务器,提供一个用于监控ActiveMQ的admin应用。<br>url:<a href="http://127.0.0.1:8161/admin/" target="_blank" rel="external">http://127.0.0.1:8161/admin/</a> 用户名和密码都是admin</p>
<p><img src="http://i.imgur.com/BHPuZPw.png" alt=""></p>
<p><img src="http://i.imgur.com/zrlOcHP.png" alt=""></p>
<p>至此,服务端启动完毕</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、简介&quot;&gt;&lt;a href=&quot;#1、简介&quot; class=&quot;headerlink&quot; title=&quot;1、简介&quot;&gt;&lt;/a&gt;1、简介&lt;/h2&gt;&lt;p&gt;ActiveMQ是一个易于使用的消息中间件(MOM:Message Orient middleware)。&lt;/p&gt;
&lt;p&gt;消息中间件有很多的用途和优点: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;将数据从一个应用程序传送到另一个应用程序,或者从软件的一个模块传送到另外一个模块; &lt;/li&gt;
&lt;li&gt;负责建立网络通信的通道,进行数据的可靠传送。 &lt;/li&gt;
&lt;li&gt;保证数据不重发,不丢失 &lt;/li&gt;
&lt;li&gt;能够实现跨平台操作,能够为不同操作系统上的软件集成技工数据传送服务&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;首先我们先说下什么是MQ,MQ英文名MessageQueue,中文名也就是大家用的消息队列,干嘛用的呢,说白了就是一个消息的接受和转发的容器,可用于消息推送。下面介绍主题,就是ActiveMQ:&lt;/p&gt;
&lt;p&gt;ActiveMQ是由Apache出品的,一款最流行的,能力强劲的开源消息总线。ActiveMQ是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,它非常快速,支持多种语言的客户端和协议,而且可以非常容易的嵌入到企业的应用环境中,并有许多高级功能。&lt;/p&gt;
</summary>
<category term="JMS" scheme="http://zhengweishan.oschina.io/categories/JMS/"/>
<category term="JMS" scheme="http://zhengweishan.oschina.io/tags/JMS/"/>
<category term="ActiveMQ" scheme="http://zhengweishan.oschina.io/tags/ActiveMQ/"/>
</entry>
<entry>
<title>JMS学习(一)-----基本概念</title>
<link href="http://zhengweishan.oschina.io/2017/01/22/JMS%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5/"/>
<id>http://zhengweishan.oschina.io/2017/01/22/JMS学习(一)基本概念/</id>
<published>2017-01-21T16:00:00.000Z</published>
<updated>2017-01-22T10:51:10.585Z</updated>
<content type="html"><![CDATA[<h2 id="1、简介"><a href="#1、简介" class="headerlink" title="1、简介"></a>1、简介</h2><p>JMS即Java消息服务(Java Message Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。</p>
<h2 id="2、体系架构"><a href="#2、体系架构" class="headerlink" title="2、体系架构"></a>2、体系架构</h2><p><strong>JMS提供者</strong>:连接面向消息中间件的,JMS接口的一个实现。提供者可以是Java平台的JMS实现,也可以是非Java平台的面向消息中间件的适配器。</p>
<p><strong>JMS客户</strong>:生产或消费基于消息的Java的应用程序或对象。</p>
<p><strong>JMS生产者</strong>:创建并发送消息的JMS客户。</p>
<p><strong>JMS消费者</strong>:接收消息的JMS客户。</p>
<p><strong>JMS消息</strong>:包括可以在JMS客户之间传递的数据的对象</p>
<p><strong>JMS队列</strong>:一个容纳那些被发送的等待阅读的消息的区域。与队列名字所暗示的意思不同,消息的接受顺序并不一定要与消息的发送顺序相同。一旦一个消息被阅读,该消息将被从队列中移走。</p>
<p><strong>JMS主题</strong>:一种支持发送消息给多个订阅者的机制。</p>
<a id="more"></a>
<h2 id="3、对象模型"><a href="#3、对象模型" class="headerlink" title="3、对象模型"></a>3、对象模型</h2><p><img src="http://i.imgur.com/oQGLPVh.gif" alt=""></p>
<p><strong>(1) ConnectionFactory(连接工厂)</strong></p>
<p>创建Connection对象的工厂,针对两种不同的jms消息模型,分别有QueueConnectionFactory和TopicConnectionFactory两种。可以通过JNDI来查找ConnectionFactory对象。</p>
<p><strong>(2) Destination(JMS目的)</strong></p>
<p>Destination的意思是消息生产者的消息发送目标或者说消息消费者的消息来源。对于消息生产者来说,它的Destination是某个队列(Queue)或某个主题(Topic);对于消息消费者来说,它的Destination也是某个队列或主题(即消息来源)。</p>
<p>所以,Destination实际上就是两种类型的对象:Queue、Topic可以通过JNDI来查找Destination。</p>
<p><strong>(3) Connection(JMS连接)</strong></p>
<p>Connection表示在客户端和JMS系统之间建立的链接(对TCP/IP socket的包装)。Connection可以产生一个或多个Session。跟ConnectionFactory一样,Connection也有两种类型:QueueConnection和TopicConnection。</p>
<p><strong>(4) Session(JMS会话)</strong></p>
<p>Session是我们操作消息的接口。可以通过session创建生产者、消费者、消息等。Session提供了事务的功能。当我们需要使用session发送/接收多个消息时,可以将这些发送/接收动作放到一个事务中。同样,也分QueueSession和TopicSession。</p>
<p><strong>(5) 消息的生产者(JMS生产者)</strong></p>
<p>消息生产者由Session创建,并用于将消息发送到Destination。同样,消息生产者分两种类型:QueueSender和TopicPublisher。可以调用消息生产者的方法(send或publish方法)发送消息。</p>
<p><strong>(6) 消息消费者(JMS消费者)</strong></p>
<p>消息消费者由Session创建,用于接收被发送到Destination的消息。两种类型:QueueReceiver和TopicSubscriber。可分别通过session的createReceiver(Queue)或createSubscriber(Topic)来创建。当然,也可以session的creatDurableSubscriber方法来创建持久化的订阅者。</p>
<p><strong>(7) MessageListener</strong></p>
<p>消息监听器。如果注册了消息监听器,一旦消息到达,将自动调用监听器的onMessage方法。EJB中的MDB(Message-Driven Bean)就是一种MessageListener。</p>
<p><strong>(8) JMS消息</strong></p>
<p>JMS消息通常有两种类型:</p>
<p>① 点对点(Point-to-Point)。在点对点的消息系统中,消息分发给一个单独的使用者。点对点消息往往与队列(javax.jms.Queue)相关联。</p>
<p>② 发布/订阅(Publish/Subscribe)。发布/订阅消息系统支持一个事件驱动模型,消息生产者和消费者都参与消息的传递。生产者发布事件,而使用者订阅感兴趣的事件,并使用事件。该类型消息一般与特定的主题(javax.jms.Topic)关联。</p>
<h2 id="4、消息类型分析"><a href="#4、消息类型分析" class="headerlink" title="4、消息类型分析"></a>4、消息类型分析</h2><p><strong>(1)Point-to-Point</strong></p>
<p><img src="http://i.imgur.com/CP8tFXO.jpg" alt=""></p>
<p>(Point-to-Point)模型是基于队列(Queue)的,对于PTP消息模型而言,它的消息目的是一个消息队列(Queue),消息生产者每次发送消息总是把消息送入消息队列中,消息消费者总是从消息队列中读取消息.先进队列的消息将先被消息消费者读取.</p>
<p>特点:</p>
<ol>
<li>每个消息只有一个消费者(Consumer)(即一旦被消费,消息就不再在消息队列中)</li>
<li>发送者和接收者之间在时间上没有依赖性,也就是说当发送者发送了消息之后,不管接收者有没有正在运行,它不会影响到消息被发送到队列</li>
<li>接收者在成功接收消息之后需向队列应答成功</li>
</ol>
<p><strong>(2)Publish/Subscribe</strong></p>
<p><img src="http://i.imgur.com/F4mjvpZ.jpg" alt=""></p>
<p>定义了如何向一个内容节点发布和订阅消息,这些节点被称作主题(topic). 主题可以被认为是消息的传输中介,发布者(publisher)发布消息到主题,订阅者(subscribe) 从主题订阅消息.主题使得消息订阅者和消息发布者保持互相独立,不需要接触即可保证消息的传送.</p>
<p>特点:</p>
<ol>
<li>每个消息可以有多个消费者</li>
<li>发布者和订阅者之间有时间上的依赖性。针对某个主题(Topic)的订阅者,它必须创建一个订阅者之后,才能消费发布者的消息,而且为了消费消息,订阅者必须保持运行的状态。</li>
<li>为了缓和这样严格的时间相关性,JMS允许订阅者创建一个可持久化的订阅。这样,即使订阅者没有被激活(运行),它也能接收到发布者的消息。</li>
</ol>
<h2 id="5、好处"><a href="#5、好处" class="headerlink" title="5、好处"></a>5、好处</h2><p>应用程序A 发送一条消息到消息服务器(也就是JMS Provider)的某个目得地(Destination),然后消息服务器把消息转发给应用程序B。因为应用程序A 和应用程序B 没有直接的代码关连,所以两者实现了解偶。如下图:</p>
<p><img src="http://i.imgur.com/ILqZigV.jpg" alt=""></p>
<p>结合上面的图总结以下三点好处:</p>
<ol>
<li>提供消息灵活性</li>
<li>松散耦合</li>
<li>异步性</li>
</ol>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、简介&quot;&gt;&lt;a href=&quot;#1、简介&quot; class=&quot;headerlink&quot; title=&quot;1、简介&quot;&gt;&lt;/a&gt;1、简介&lt;/h2&gt;&lt;p&gt;JMS即Java消息服务(Java Message Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。&lt;/p&gt;
&lt;h2 id=&quot;2、体系架构&quot;&gt;&lt;a href=&quot;#2、体系架构&quot; class=&quot;headerlink&quot; title=&quot;2、体系架构&quot;&gt;&lt;/a&gt;2、体系架构&lt;/h2&gt;&lt;p&gt;&lt;strong&gt;JMS提供者&lt;/strong&gt;:连接面向消息中间件的,JMS接口的一个实现。提供者可以是Java平台的JMS实现,也可以是非Java平台的面向消息中间件的适配器。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS客户&lt;/strong&gt;:生产或消费基于消息的Java的应用程序或对象。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS生产者&lt;/strong&gt;:创建并发送消息的JMS客户。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS消费者&lt;/strong&gt;:接收消息的JMS客户。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS消息&lt;/strong&gt;:包括可以在JMS客户之间传递的数据的对象&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS队列&lt;/strong&gt;:一个容纳那些被发送的等待阅读的消息的区域。与队列名字所暗示的意思不同,消息的接受顺序并不一定要与消息的发送顺序相同。一旦一个消息被阅读,该消息将被从队列中移走。&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;JMS主题&lt;/strong&gt;:一种支持发送消息给多个订阅者的机制。&lt;/p&gt;
</summary>
<category term="JMS" scheme="http://zhengweishan.oschina.io/categories/JMS/"/>
<category term="JMS" scheme="http://zhengweishan.oschina.io/tags/JMS/"/>
<category term="ActiveMQ" scheme="http://zhengweishan.oschina.io/tags/ActiveMQ/"/>
</entry>
<entry>
<title>使用Hexo+OSChina+git搭建自己的博客网站</title>
<link href="http://zhengweishan.oschina.io/2017/01/22/Hexo+OSChina/"/>
<id>http://zhengweishan.oschina.io/2017/01/22/Hexo+OSChina/</id>
<published>2017-01-21T16:00:00.000Z</published>
<updated>2017-01-22T03:50:05.209Z</updated>
<content type="html"><![CDATA[<h1 id="基础工具介绍"><a href="#基础工具介绍" class="headerlink" title="基础工具介绍"></a>基础工具介绍</h1><h3 id="码云Pages"><a href="#码云Pages" class="headerlink" title="码云Pages"></a>码云Pages</h3><p>码云 Pages 是一个免费的静态网页托管服务,您可以使用码云 Pages 托管博客、项目官网等静态网页。如果您使用过 Github Pages 那么您会很快上手使用码云的Pages服务。</p>
<p>官方介绍:<a href="http://www.oschina.net/news/73980/gitosc-pages" target="_blank" rel="external">http://www.oschina.net/news/73980/gitosc-pages</a></p>
<h3 id="Hexo"><a href="#Hexo" class="headerlink" title="Hexo"></a>Hexo</h3><p>Hexo 是一个简单地、轻量地、基于Node的一个静态博客框架,可以方便的生成静态网页托管在github和Heroku上,引用Hexo作者 <a href="https://github.com/hexojs/hexo" target="_blank" rel="external">[@tommy351]</a> 的话:</p>
<p>快速、简单且功能强大的 Node.js 博客框架。A fast, simple &amp; powerful blog framework, powered by Node.js.</p>
<p>官网地址:<a href="https://hexo.io" target="_blank" rel="external">https://hexo.io</a></p>
<h3 id="git"><a href="#git" class="headerlink" title="git"></a>git</h3><p>Git是一个开源的分布式版本控制系统,用以有效、高速的处理从很小到非常大的项目版本管理。</p>
<p>官网地址:<a href="https://git-scm.com" target="_blank" rel="external">https://git-scm.com</a><br><a id="more"></a></p>
<h1 id="搭建环境"><a href="#搭建环境" class="headerlink" title="搭建环境"></a>搭建环境</h1><h3 id="码云Pages使用"><a href="#码云Pages使用" class="headerlink" title="码云Pages使用"></a>码云Pages使用</h3><p>这里使用开源中国码云,没有使用github(你懂的,支持下国内软件),没有开源中国码云的小伙伴赶紧注册了。具体可以参见 :<a href="http://www.oschina.net/news/73980/gitosc-pages" target="_blank" rel="external">官网</a> 的介绍以及使用,这里就不在啰里啰嗦的介绍了。</p>
<p>因为我想以根目录访问网站,所以我创建了一个这样子的项目:</p>
<p><a href="https://git.oschina.net/zhengweishan/zhengweishan" target="_blank" rel="external">https://git.oschina.net/zhengweishan/zhengweishan</a>.</p>
<p>启动码云Pages,就可以访问了,访问地址:</p>
<p><a href="http://zhengweishan.oschina.io/">http://zhengweishan.oschina.io/</a></p>
<p>官方说明如下:</p>
<p><strong>*如果你想以根目录的形式访问自己的静态网站,只需要建立一个与自己个性地址同名的项目即可,如<a href="http://git.oschina.net/ipvb" target="_blank" rel="external">http://git.oschina.net/ipvb</a> 这个用户,想要创建一个自己的站点,但不想以子目录的方式访问,想以ipvb.oschina.io 直接访问,那么他就可以创建一个名字为ipvb的项目<a href="http://git.oschina.net/ipvb/ipvb" target="_blank" rel="external">http://git.oschina.net/ipvb/ipvb</a> 部署完成后,就可以以<a href="http://ipvb.oschina.io" target="_blank" rel="external">http://ipvb.oschina.io</a> 进行访问了。</strong> *</p>
<h3 id="git安装"><a href="#git安装" class="headerlink" title="git安装"></a>git安装</h3><p>请参考<a href="http://www.runoob.com/git/git-install-setup.html" target="_blank" rel="external">http://www.runoob.com/git/git-install-setup.html</a>,这里就不在累赘的介绍了。</p>
<h3 id="Node-js安装"><a href="#Node-js安装" class="headerlink" title="Node.js安装"></a>Node.js安装</h3><p>请参考<a href="http://www.runoob.com/nodejs/nodejs-install-setup.html" target="_blank" rel="external">http://www.runoob.com/nodejs/nodejs-install-setup.html</a>,这里就不在累赘的介绍了。可能有人会问:为什么要安装Node.js?很简单嘛,我们的Hexo是基于Node的一个静态博客框架嘛。</p>
<h3 id="Hexo安装"><a href="#Hexo安装" class="headerlink" title="Hexo安装"></a>Hexo安装</h3><ul>
<li><p><strong>安装</strong></p>
<p> 如果您的电脑中已经安装上述必备程序,那么恭喜您!接下来只需要使用 npm 即可完成 Hexo 的安装(可以参看<a href="https://hexo.io/zh-cn/docs/" target="_blank" rel="external">官网文档</a>)。打开命令窗口输入下面代码:</p>
<p> <code>npm install hexo-cli -g</code></p>
<p> 安装成功后输入hexo 如果得到下面这个结果,恭喜你!安装成功!</p>
<p> <img src="http://i.imgur.com/W3lmqUy.png" alt=""></p>
<p> Hexo常用命令请参考:<a href="https://hexo.io/zh-cn/docs/commands.html" target="_blank" rel="external">https://hexo.io/zh-cn/docs/commands.html</a></p>
</li>
<li><p><strong>本地运行</strong></p>
<p> 安装 Hexo 完成后,Hexo 将会在指定文件夹中新建所需要的文件。这里本地先新建了与博客地址一样的文件夹:<br> zhengweishan.oschina.io.然后请进入你创建的改文件夹的上级目录,在该目录下打开命令行窗口,依次执行下列命令:</p>
<ol>
<li><code>hexo init zhengweishan.oschina.io</code></li>
<li><code>cd zhengweishan.oschina.io</code></li>
<li><code>npm install #install before start blogging</code></li>
<li><p><code>hexo generate #生成静态文件到项目根目录的public文件夹中</code></p>
<p>新建完成后,指定文件夹的目录如下:</p>
<p><strong>.</strong></p>
<p>├── .deploy #需要部署的文件</p>
<p>├── node_modules #Hexo插件</p>
<p>├── public #生成的静态网页文件</p>
<p>├── scaffolds #模板</p>
<p>├── source #博客正文和其他源文件, 404 favicon CNAME 等都应该放在这里</p>
<p>| ├── _drafts #草稿</p>
<p>| └── _posts #文章</p>
<p>├── themes #主题</p>
<p>├── _config.yml #全局配置文件</p>
<p>└── package.json</p>
<p>进行到这步后就可以先在本地运行下,看看效果了。执行下面命令:</p>
</li>
<li><p><code>cd zhengweishan.oschina.io</code></p>
</li>
<li><code>npm install #install before start blogging</code></li>
<li><p><code>hexo server #运行本地服务</code></p>
<p>浏览器输入<a href="http://localhost:4000" target="_blank" rel="external">http://localhost:4000</a>就可以看到效果。如下:</p>
<p><img src="http://i.imgur.com/Umw13aq.png" alt=""></p>
</li>
</ol>
</li>
<li><p><strong>远程发布</strong></p>
<p> 注册一个码云帐号,并创建一个项目,这里使用已经创建好的项目<a href="https://git.oschina.net/zhengweishan/zhengweishan" target="_blank" rel="external">https://git.oschina.net/zhengweishan/zhengweishan</a>,然后获取git地址:<a href="https://git.oschina.net/zhengweishan/zhengweishan.git" target="_blank" rel="external">https://git.oschina.net/zhengweishan/zhengweishan.git</a></p>
<p> 这里使用git将项目中public文件夹下的文件管理起来,并推送到码云上。借用一个插件来帮助我们完成,安装 hexo-deployer-git。安装代码如下:<br> <code>npm install hexo-deployer-git --save</code><br> 配置项目根目录_config.yml 文件,修改deploy的值,如下图:</p>
<p> <img src="http://i.imgur.com/7eS6yvB.png" alt=""> </p>
<p> 参考:<a href="https://hexo.io/docs/deployment.html" target="_blank" rel="external">https://hexo.io/docs/deployment.html</a></p>
<p> 修改完后在命令窗口执行下面命令:</p>
<ol>
<li><code>cd zhengweishan.oschina.io</code></li>
<li><code>npm install #install before start blogging</code></li>
<li><p><code>hexo deploy #一键部署功能</code></p>
<p>之后会弹出一个对话框,输入码云的帐号密码。大家最后在安装好git以后配置一个全局的文件,这样就可以不用每次提交都输入账号密码了。</p>
<p>部署成功之后,登录码云,查看之前创建的项目中出现了public文件夹中的文件,这时候代表之前的部署是成功的。</p>
<p>最后启动码云的Pages功能,详细参看:<a href="http://www.oschina.net/news/73980/gitosc-pages" target="_blank" rel="external">http://www.oschina.net/news/73980/gitosc-pages</a></p>
<p>启动之后如下图,</p>
<p><img src="http://i.imgur.com/qWvBXKb.png" alt=""></p>
<p>然后浏览器输入生成的网址就可以访问了,如下图所示:</p>
<p><img src="http://i.imgur.com/r6WAvKY.png" alt=""></p>
</li>
</ol>
</li>
</ul>
<p>看到之前和本地启动一样的效果了,这样子博客网站就部署完成了。</p>
]]></content>
<summary type="html">
&lt;h1 id=&quot;基础工具介绍&quot;&gt;&lt;a href=&quot;#基础工具介绍&quot; class=&quot;headerlink&quot; title=&quot;基础工具介绍&quot;&gt;&lt;/a&gt;基础工具介绍&lt;/h1&gt;&lt;h3 id=&quot;码云Pages&quot;&gt;&lt;a href=&quot;#码云Pages&quot; class=&quot;headerlink&quot; title=&quot;码云Pages&quot;&gt;&lt;/a&gt;码云Pages&lt;/h3&gt;&lt;p&gt;码云 Pages 是一个免费的静态网页托管服务,您可以使用码云 Pages 托管博客、项目官网等静态网页。如果您使用过 Github Pages 那么您会很快上手使用码云的Pages服务。&lt;/p&gt;
&lt;p&gt;官方介绍:&lt;a href=&quot;http://www.oschina.net/news/73980/gitosc-pages&quot;&gt;http://www.oschina.net/news/73980/gitosc-pages&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;Hexo&quot;&gt;&lt;a href=&quot;#Hexo&quot; class=&quot;headerlink&quot; title=&quot;Hexo&quot;&gt;&lt;/a&gt;Hexo&lt;/h3&gt;&lt;p&gt;Hexo 是一个简单地、轻量地、基于Node的一个静态博客框架,可以方便的生成静态网页托管在github和Heroku上,引用Hexo作者 &lt;a href=&quot;https://github.com/hexojs/hexo&quot;&gt;[@tommy351]&lt;/a&gt; 的话:&lt;/p&gt;
&lt;p&gt;快速、简单且功能强大的 Node.js 博客框架。A fast, simple &amp;amp; powerful blog framework, powered by Node.js.&lt;/p&gt;
&lt;p&gt;官网地址:&lt;a href=&quot;https://hexo.io&quot;&gt;https://hexo.io&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;git&quot;&gt;&lt;a href=&quot;#git&quot; class=&quot;headerlink&quot; title=&quot;git&quot;&gt;&lt;/a&gt;git&lt;/h3&gt;&lt;p&gt;Git是一个开源的分布式版本控制系统,用以有效、高速的处理从很小到非常大的项目版本管理。&lt;/p&gt;
&lt;p&gt;官网地址:&lt;a href=&quot;https://git-scm.com&quot;&gt;https://git-scm.com&lt;/a&gt;&lt;br&gt;
</summary>
<category term="Hexo" scheme="http://zhengweishan.oschina.io/categories/Hexo/"/>
<category term="Hexo" scheme="http://zhengweishan.oschina.io/tags/Hexo/"/>
</entry>
<entry>
<title>JAVA常用开发环境配置</title>
<link href="http://zhengweishan.oschina.io/2017/01/22/java%E5%B8%B8%E7%94%A8%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE/"/>
<id>http://zhengweishan.oschina.io/2017/01/22/java常用开发环境配置/</id>
<published>2017-01-21T16:00:00.000Z</published>
<updated>2017-01-22T10:40:15.897Z</updated>
<content type="html"><![CDATA[<h2 id="1、jdk配置"><a href="#1、jdk配置" class="headerlink" title="1、jdk配置"></a>1、jdk配置</h2><h3 id="1、1下载安装"><a href="#1、1下载安装" class="headerlink" title="1、1下载安装"></a>1、1下载安装</h3><p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html" target="_blank" rel="external">http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html</a> 下载安装就好(选择和你系统一样的版本32位或者64位)</p>
<h3 id="1、2环境配置"><a href="#1、2环境配置" class="headerlink" title="1、2环境配置"></a>1、2环境配置</h3><pre><code>计算机--&gt;属性--&gt;高级系统设置--&gt;环境变量
</code></pre><p><img src="http://i.imgur.com/xP2tKUb.png" alt=""></p>
<pre><code>在系统变量中新建 变量名:JAVA_HOME
变量值:C:\Program Files\Java\jdk1.7.0_80 (ps:如果你没有改变默认路径复制就可以,如果修改过请选择jdk的安装目录)
JAVA_HOME是用来表示jdk的安装目录。
</code></pre><p><img src="http://i.imgur.com/VHMZxz7.png" alt=""></p>
<pre><code>配置JAVA_HOME的原因是:(1)方便引用。(2)其他软件会引用约定好的JAVA_HOME变量。比如tomcat就需要引用JAVA_HOME。
在系统变量中查找 Path 编辑
追加新的变量值:%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
</code></pre><p><img src="http://i.imgur.com/BGVgS7z.png" alt=""></p>
<pre><code>在系统变量中新建
变量名:CLASSPATH
变量值:.;%JAVA_HOME%lib;%JAVA_HOME%lib\tools.jar;
(ps:前面有个 .; 这个是告诉JDK,搜索CLASS时先查找当前目录的CLASS文件 )
</code></pre><p><img src="http://i.imgur.com/1IRscXU.png" alt=""></p>
<pre><code>验证是否成功
win+R 输入cmd 进入命令提示符界面
输入java -version (ps:java空格-version)
查看当前jdk的版本,显示版本信息 则说明安装和配置成功。
</code></pre><p><img src="http://i.imgur.com/DE1ZqFN.png" alt=""><br><a id="more"></a></p>
<h2 id="2、tomcat配置"><a href="#2、tomcat配置" class="headerlink" title="2、tomcat配置"></a>2、tomcat配置</h2><h3 id="2、1下载安装"><a href="#2、1下载安装" class="headerlink" title="2、1下载安装"></a>2、1下载安装</h3><p><a href="http://tomcat.apache.org/download-70.cgi" target="_blank" rel="external">http://tomcat.apache.org/download-70.cgi</a> 下载解压到你指定的地方,选择和你系统一样的版本32位或者64位<br>下载页面:<br><img src="http://i.imgur.com/ISuO7w4.png" alt=""></p>
<h3 id="2、2环境配置"><a href="#2、2环境配置" class="headerlink" title="2、2环境配置"></a>2、2环境配置</h3><pre><code>步骤同1.2
在系统变量中新建 变量名:CATALINA_HOME
变量值:S:\devTools\apache-tomcat-7.0.69
</code></pre><p><img src="http://i.imgur.com/ks0ds4b.png" alt=""></p>
<pre><code>在系统变量中查找 CLASSPATH 编辑
追加新的变量值:%CATALINA_HOME%\common\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
</code></pre><p><img src="http://i.imgur.com/zKplzau.png" alt=""></p>
<pre><code>在系统变量中查找 Path 编辑
追加新的变量值:%CATALINA_HOME%\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
</code></pre><p><img src="http://i.imgur.com/iNopGL6.png" alt=""></p>
<pre><code>验证是否成功
找到安装路径下的bin 文件夹,找到里面的startup.bat执行文件,运行,然后执行下面的操作。
打开浏览器,输入http://localhost:8080.如果出现下面的内容说明成功了。
</code></pre><p><img src="http://i.imgur.com/zYt9sLQ.png" alt=""></p>
<h2 id="3、maven配置"><a href="#3、maven配置" class="headerlink" title="3、maven配置"></a>3、maven配置</h2><h3 id="3、1下载安装"><a href="#3、1下载安装" class="headerlink" title="3、1下载安装"></a>3、1下载安装</h3><p><a href="https://maven.apache.org/download.cgi" target="_blank" rel="external">https://maven.apache.org/download.cgi</a> 下载解压到指定的地方就可以。下载页面:<br><img src="http://i.imgur.com/IFsu1oD.png" alt=""></p>
<h3 id="3、2环境配置"><a href="#3、2环境配置" class="headerlink" title="3、2环境配置"></a>3、2环境配置</h3><pre><code>步骤同1.2
在系统变量中新建 变量名:MAVEN_HOME
变量值:S:\devTools\apache-maven-3.2.3
</code></pre><p><img src="http://i.imgur.com/MuV95kj.png" alt=""></p>
<pre><code>在系统变量中查找 Path 编辑
追加新的变量值:%MAVEN_HOME%\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
</code></pre><p><img src="http://i.imgur.com/ZCSj31a.png" alt=""></p>
<pre><code>验证是否成功
win+R 输入cmd 进入命令提示符界面
输入mvn -version (ps:mvn空格-version)
查看当前mvn的版本,显示版本信息 则说明安装和配置成功。
</code></pre><p><img src="http://i.imgur.com/i2ekoy0.png" alt=""></p>
<h2 id="4、ant配置"><a href="#4、ant配置" class="headerlink" title="4、ant配置"></a>4、ant配置</h2><h3 id="4、1下载安装"><a href="#4、1下载安装" class="headerlink" title="4、1下载安装"></a>4、1下载安装</h3><p><a href="http://ant.apache.org/bindownload.cgi" target="_blank" rel="external">http://ant.apache.org/bindownload.cgi</a> 下载解压到指定的地方就可以。下载页面:<br><img src="http://i.imgur.com/H2P91Xr.png" alt=""></p>
<h3 id="4、2环境配置"><a href="#4、2环境配置" class="headerlink" title="4、2环境配置"></a>4、2环境配置</h3><pre><code>步骤同1.2
在系统变量中新建 变量名:ANT_HOME
变量值:S:\devTools\apache-ant-1.9.7
</code></pre><p><img src="http://i.imgur.com/lAwWl0y.png" alt=""></p>
<pre><code>在系统变量中查找 Path 编辑
追加新的变量值:%ANT_HOME%\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
</code></pre><p><img src="http://i.imgur.com/zH4WBl5.png" alt=""></p>
<pre><code>验证是否成功
win+R 输入cmd 进入命令提示符界面
输入ant -version (ps:ant空格-version)
查看当前mvn的版本,显示版本信息 则说明安装和配置成功。
</code></pre><p><img src="http://i.imgur.com/6CT2akK.png" alt=""></p>
<h2 id="5、eclipse整合maven配置"><a href="#5、eclipse整合maven配置" class="headerlink" title="5、eclipse整合maven配置"></a>5、eclipse整合maven配置</h2><p>参考我的博客:<a href="http://my.oschina.net/zhengweishan/blog/690195" target="_blank" rel="external">eclipse创建maven多模块项目</a> 第三部分:<a href="http://my.oschina.net/zhengweishan/blog/690195" target="_blank" rel="external">Eclipse配置maven</a></p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、jdk配置&quot;&gt;&lt;a href=&quot;#1、jdk配置&quot; class=&quot;headerlink&quot; title=&quot;1、jdk配置&quot;&gt;&lt;/a&gt;1、jdk配置&lt;/h2&gt;&lt;h3 id=&quot;1、1下载安装&quot;&gt;&lt;a href=&quot;#1、1下载安装&quot; class=&quot;headerlink&quot; title=&quot;1、1下载安装&quot;&gt;&lt;/a&gt;1、1下载安装&lt;/h3&gt;&lt;p&gt;&lt;a href=&quot;http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html&quot;&gt;http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html&lt;/a&gt; 下载安装就好(选择和你系统一样的版本32位或者64位)&lt;/p&gt;
&lt;h3 id=&quot;1、2环境配置&quot;&gt;&lt;a href=&quot;#1、2环境配置&quot; class=&quot;headerlink&quot; title=&quot;1、2环境配置&quot;&gt;&lt;/a&gt;1、2环境配置&lt;/h3&gt;&lt;pre&gt;&lt;code&gt;计算机--&amp;gt;属性--&amp;gt;高级系统设置--&amp;gt;环境变量
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/xP2tKUb.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;在系统变量中新建 变量名:JAVA_HOME
变量值:C:\Program Files\Java\jdk1.7.0_80 (ps:如果你没有改变默认路径复制就可以,如果修改过请选择jdk的安装目录)
JAVA_HOME是用来表示jdk的安装目录。
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/VHMZxz7.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;配置JAVA_HOME的原因是:(1)方便引用。(2)其他软件会引用约定好的JAVA_HOME变量。比如tomcat就需要引用JAVA_HOME。
在系统变量中查找 Path 编辑
追加新的变量值:%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;
(ps:原来Path的变量值末尾如果没有;号,先输入;号再输入上面的代码)
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/BGVgS7z.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;在系统变量中新建
变量名:CLASSPATH
变量值:.;%JAVA_HOME%lib;%JAVA_HOME%lib\tools.jar;
(ps:前面有个 .; 这个是告诉JDK,搜索CLASS时先查找当前目录的CLASS文件 )
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/1IRscXU.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;验证是否成功
win+R 输入cmd 进入命令提示符界面
输入java -version (ps:java空格-version)
查看当前jdk的版本,显示版本信息 则说明安装和配置成功。
&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;&lt;img src=&quot;http://i.imgur.com/DE1ZqFN.png&quot; alt=&quot;&quot;&gt;&lt;br&gt;
</summary>
<category term="JAVA" scheme="http://zhengweishan.oschina.io/categories/JAVA/"/>
<category term="JAVA" scheme="http://zhengweishan.oschina.io/tags/JAVA/"/>
</entry>
<entry>
<title>JVM简介及工作原理分析</title>
<link href="http://zhengweishan.oschina.io/2017/01/20/jvm/"/>
<id>http://zhengweishan.oschina.io/2017/01/20/jvm/</id>
<published>2017-01-19T16:00:00.000Z</published>
<updated>2017-01-20T07:23:48.909Z</updated>
<content type="html"><![CDATA[<h2 id="1、什么是JVM"><a href="#1、什么是JVM" class="headerlink" title="1、什么是JVM"></a>1、什么是JVM</h2><p>JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。</p>
<p>简单来说,JVM是用于执行Java应用程序和字节码的软件模块,并且可以将字节码转换为特定硬件和特定操作系统的本地代码。JVM在执行字节码时,实际上最终还是把字节码解释成具体平台上的机器指令执行,这就是Java的能够“一次编译,到处运行”的原因。</p>
<p>JVM包括一套字节码指令集、一组寄存器、一个栈、一个垃圾回收堆和一个存储方法域。</p>
<h2 id="2、JRE-JDK-JVM是什么关系"><a href="#2、JRE-JDK-JVM是什么关系" class="headerlink" title="2、JRE/JDK/JVM是什么关系"></a>2、JRE/JDK/JVM是什么关系</h2><p>JRE(JavaRuntimeEnvironment,Java运行环境),也就是Java平台。所有的Java 程序都要在JRE下才能运行。普通用户只需要运行已开发好的java程序,安装JRE即可。</p>
<p>JDK(Java Development Kit)是程序开发者用来来编译、调试java程序用的开发工具包。JDK的工具也是Java程序,也需要JRE才能运行。为了保持JDK的独立性和完整性,在JDK的安装过程中,JRE也是 安装的一部分。所以,在JDK的安装目录下有一个名为jre的目录,用于存放JRE文件。</p>
<p>JVM(JavaVirtualMachine,Java虚拟机)是JRE的一部分。它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。JVM有自己完善的硬件架构,如处理器、堆栈、寄存器等,还具有相应的指令系统。Java语言最重要的特点就是跨平台运行。使用JVM就是为了支持与操作系统无关,实现跨平台。<a id="more"></a></p>
<h2 id="3、JVM体系结构"><a href="#3、JVM体系结构" class="headerlink" title="3、JVM体系结构"></a>3、JVM体系结构</h2><p><img src="http://i.imgur.com/5JmCfMv.jpg" alt=""></p>
<p>JVM的内部体系结构分为三部分(图片来自网络):</p>
<p>(1)类装载器(ClassLoader)子系统</p>
<pre><code>用来装载.class文件
</code></pre><p>(2)执行引擎</p>
<pre><code>执行字节码,或者执行本地方法
</code></pre><p>(3)运行时数据区</p>
<pre><code>方法区,堆,java栈,PC寄存器,本地方法栈
</code></pre><h2 id="4、JVM工作原理"><a href="#4、JVM工作原理" class="headerlink" title="4、JVM工作原理"></a>4、JVM工作原理</h2><p>JVM是java的核心和基础,在java编译器和os平台之间的虚拟处理器。它是一种基于下层的操作系统和硬件平台并利用软件方法来实现的抽象的计算机,可以在上面执行java的字节码程序。java编译器只需面向JVM,生成JVM能理解的代码或字节码文件。Java源文件经编译器,编译成字节码程序,通过JVM将每一条指令翻译成不同平台机器码,通过特定平台运行。可以用下图来表示编译执行的简化过程:</p>
<p><img src="http://i.imgur.com/ALjoef3.png" alt=""></p>
<h2 id="5、JVM执行过程"><a href="#5、JVM执行过程" class="headerlink" title="5、JVM执行过程"></a>5、JVM执行过程</h2><blockquote>
<p>1、加载class文件;</p>
<p>2、分配内存;</p>
<p>3、解释字节码成机器码;</p>
<p>4、运行过程垃圾收集;</p>
<p>5、结束。</p>
</blockquote>
<p>JRE(java运行时环境)由JVM构造的java程序的运行环,也是Java程序运行的环境,但是他同时一个操作系统的一个应用程序一个进程,因此他也有他自己的运行的生命周期,也有自己的代码和数据空间。</p>
<p>JVM在整个jdk中处于最底层,负责于操作系统的交互,用来屏蔽操作系统环境,提供一个完整的Java运行环境,因此也就虚拟计算机。 操作系统装入JVM是通过jdk中Java.exe来完成,通过下面4步来完成JVM环境:</p>
<blockquote>
<p>1) 创建JVM装载环境和配置 </p>
<p>2) 装载JVM.dll </p>
<p>3) 初始化JVM.dll并挂界到JNIENV(JNI调用接口)实例</p>
<p>4) 调用JNIEnv实例装载并处理class类。</p>
</blockquote>
<h2 id="6、JVM的生命周期"><a href="#6、JVM的生命周期" class="headerlink" title="6、JVM的生命周期"></a>6、JVM的生命周期</h2><h3 id="a、两个概念"><a href="#a、两个概念" class="headerlink" title="a、两个概念"></a>a、两个概念</h3><p>JVM实例和JVM执行引擎实例</p>
<blockquote>
<ul>
<li><p>JVM实例对应了一个独立运行的Java程序 (进程级别)</p>
</li>
<li><p>JVM执行引擎实例则对应了属于用户运行程序的线程 (线程级别)</p>
</li>
</ul>
</blockquote>
<h3 id="b、JVM的生命周期"><a href="#b、JVM的生命周期" class="headerlink" title="b、JVM的生命周期"></a>b、JVM的生命周期</h3><blockquote>
<p>JVM实例的诞生</p>
</blockquote>
<p> 当启动一个Java程序时,一个JVM实例就产生了,任何一个拥有public static void main(String[] args)函数的class都可以作为JVM实例运行的起点</p>
<blockquote>
<p>JVM实例的运行</p>
</blockquote>
<p> main()作为该程序初始线程的起点,任何其他线程均由该线程启动。JVM内部有两种线程:守护线程和非守护线程,main()属于非守护线程,守护线程通常由JVM自己使用,java程序也可以标明自己创建的线程是守护线程。</p>
<blockquote>
<p>JVM实例的消亡</p>
</blockquote>
<p>当程序中的所有非守护线程都终止时,JVM才退出;若安全管理器允许,程 序也可以使用Runtime类或者System.exit()来退出。</p>
<h2 id="7、ClassLoader(类加载器)"><a href="#7、ClassLoader(类加载器)" class="headerlink" title="7、ClassLoader(类加载器)"></a>7、ClassLoader(类加载器)</h2><h3 id="a、JVM整个类加载过程"><a href="#a、JVM整个类加载过程" class="headerlink" title="a、JVM整个类加载过程"></a>a、JVM整个类加载过程</h3><p>JVM将整个类加载过程划分为了三个步骤:</p>
<p><strong><em>(1)装载</em></strong></p>
<p> 装载过程负责找到二进制字节码并加载至JVM中,JVM通过类名、类所在的包名通过ClassLoader来完成类的加载,同样,也采用以上三个元素来标识一个被加载了的类:类名+包名+ClassLoader实例ID。</p>
<p><strong><em>(2)链接</em></strong></p>
<p> 链接过程负责对二进制字节码的格式进行校验、初始化装载类中的静态变量以及解析类中调用的接口、类。在完成了校验后,JVM初始化类中的静态变量,并将其值赋为默认值。最后一步为对类中的所有属性、方法进行验证,以确保其需要调用的属性、方法存在,以及具备应的权限(例如public、private域权限等),会造成NoSuchMethodError、NoSuchFieldError等错误信息。</p>
<p><strong><em>(3)初始化</em></strong></p>
<p> 初始化过程即为执行类中的静态初始化代码、构造器代码以及静态属性的初始化,在四种情况下初始化过程会被触发执行:</p>
<ol>
<li>调用了new;</li>
<li>反射调用了类中的方法;</li>
<li>子类调用了初始化;</li>
<li>JVM启动过程中指定的初始化类。</li>
</ol>
<h3 id="b、JVM类加载顺序"><a href="#b、JVM类加载顺序" class="headerlink" title="b、JVM类加载顺序"></a>b、JVM类加载顺序</h3><p>JVM有两种类加载器:</p>
<blockquote>
<ul>
<li><p>启动类装载器:是JVM实现的一部分</p>
</li>
<li><p>用户自定义类装载器:是Java程序的一部分,必须是ClassLoader类的子类</p>
</li>
</ul>
</blockquote>
<p>当JVM启动时,由Bootstrap向User-Defined方向加载类;应用进行ClassLoader时,由User-Defined向Bootstrap方向查找并加载类;</p>
<p><strong>1. Bootstrap ClassLoader</strong></p>
<p>这是JVM的根ClassLoader,它是用C++实现的,JVM启动时初始化此ClassLoader,并由此ClassLoader完成$JAVA_HOME中jre/lib/rt.jar(Sun JDK的实现)中所有class文件的加载,这个jar中包含了java规范定义的所有接口以及实现。</p>
<p><strong>2. Extension ClassLoader</strong></p>
<p>JVM用此classloader来加载扩展功能的一些jar包。</p>
<p><strong>3. System ClassLoader</strong></p>
<p>JVM用此classloader来加载启动参数中指定的Classpath中的jar包以及目录,在Sun JDK中ClassLoader对应的类名为AppClassLoader。</p>
<p><strong>4. User-Defined ClassLoader</strong></p>
<p>User-DefinedClassLoader是Java开发人员继承ClassLoader抽象类自行实现的ClassLoader,基于自定义的ClassLoader可用于加载非Classpath中的jar以及目录。</p>
<p>有关ClassLoader抽象类的几个关键方法:</p>
<blockquote>
<p><strong>loadClass</strong></p>
</blockquote>
<p>此方法负责加载指定名字的类,ClassLoader的实现方法为先从已经加载的类中寻找,如没有则继续从parent ClassLoader中寻找,如仍然没找到,则从System ClassLoader中寻找,最后再调用findClass方法来寻找,如要改变类的加载顺序,则可覆盖此方法</p>
<blockquote>
<p><strong>findLoadedClass</strong></p>
</blockquote>
<p>此方法负责从当前ClassLoader实例对象的缓存中寻找已加载的类,调用的为native的方法。</p>
<blockquote>
<p><strong>findClass</strong></p>
</blockquote>
<p>此方法直接抛出ClassNotFoundException,因此需要通过覆盖loadClass或此方法来以自定义的方式加载相应的类。</p>
<blockquote>
<p><strong>findSystemClass</strong></p>
</blockquote>
<p>此方法负责从System ClassLoader中寻找类,如未找到,则继续从Bootstrap ClassLoader中寻找,如仍然为找到,则返回null。</p>
<blockquote>
<p><strong>defineClass</strong></p>
</blockquote>
<p>此方法负责将二进制的字节码转换为Class对象</p>
<blockquote>
<p><strong>resolveClass</strong></p>
</blockquote>
<p>此方法负责完成Class对象的链接,如已链接过,则会直接返回。</p>
<h2 id="8、执行引擎"><a href="#8、执行引擎" class="headerlink" title="8、执行引擎"></a>8、执行引擎</h2><p>JVM通过执行引擎来完成字节码的执行,在执行过程中JVM采用的是自己的一套指令系统,每个线程在创建后,都会产生一个程序计数器(pc)和栈(Stack),其中程序计数器中存放了下一条将要执行的指令,Stack中存放Stack Frame,表示的为当前正在执行的方法,每个方法的执行都会产生Stack Frame,Stack Frame中存放了传递给方法的参数、方法内的局部变量以及操作数栈,操作数栈用于存放指令运算的中间结果,指令负责从操作数栈中弹出参与运算的操作数,指令执行完毕后再将计算结果压回到操作数栈,当方法执行完毕后则从Stack中弹出,继续其他方法的执行。</p>
<p>在执行方法时JVM提供了四种指令来执行:</p>
<blockquote>
<p>(1)invokestatic:调用类的static方法</p>
<p>(2)invokevirtual:调用对象实例的方法</p>
<p>(3)invokeinterface:将属性定义为接口来进行调用</p>
<p>(4)invokespecial:JVM对于初始化对象(Java构造器的方法为:<init>)以及调用对象实例中的私有方法时。</init></p>
</blockquote>
<p>主要的执行技术有:解释,即时编译,自适应优化、芯片级直接执行</p>
<blockquote>
<p>(1)解释属于第一代JVM,</p>
<p>(2)即时编译JIT属于第二代JVM,</p>
<p>(3)自适应优化(目前Sun的HotspotJVM采用这种技术)则吸取第一代JVM和第二代JVM的经验,采用两者结合的方式开始对所有的代码都采取解释执行的方式,并监视代码执行情况,然后对那些经常调用的方法启动一个后台线程,将其编译为本地代码,并进行优化。若方法不再频繁使用,则取消编译过的代码,仍对其进行解释执行。</p>
</blockquote>
<h2 id="9、JVM运行时数据区"><a href="#9、JVM运行时数据区" class="headerlink" title="9、JVM运行时数据区"></a>9、JVM运行时数据区</h2><p><img src="http://i.imgur.com/6XGqJJq.png" alt=""></p>
<blockquote>
<p><strong>PC寄存器(Program Counter Register)</strong></p>
</blockquote>
<p>(Program Counter Register)是一块较小的内存空间,它可以看做是当前线程所执行的字节码的行号指示器。在虚拟机的概念模型里(仅是概念模型,各种虚拟机可能会通过一些更高效的方式去实现),字节码解释器工作时就是通过改变这个计数器的值来选取下一条需要执行的字节码指令、分支、循环、跳转、异常处理、线程恢复等基础功能都需要依赖这个计数器来完成。 </p>
<p>由于Java虚拟机的多线程是通过线程轮流切换并分配处理器执行时间的方式来实现的。在任何一个确定的时刻,一个处理器都只会执行一条线程中的指令。因此,为了线程切换后能恢复到正确的执行位置,每条线程都需要有一个独立的程序计数器,各个线程之间计数器互不影响,独立存储。 </p>
<p>如果线程正在执行的是一个Java方法,那这个计数器记录的是正在执行的字节码指令的地址;如果正在执行的是Native方法,这个计数器值则为空(undefined)。<br>此内存区域是唯一一个在Java虚拟机规范中没有规定任何OutOfMemoryError情况的区域。 </p>
<p>程序计数器是线程私有的,它的生命周期与线程相同(随线程而生,随线程而灭)。</p>
<blockquote>
<p><strong>JVM栈(JVM Stacks)</strong></p>
</blockquote>
<p> 每个JVM 线程都有一个私有的JVM 栈(Stacks),它将和线程同时创建。JVM 栈用来存储帧(后面会讲解)。JVM 栈类似于传统语言例如C 的栈,它持有局部变量和部分结果并且参与方法的调用和返回。 由于JVM 栈除了压入弹出帧外不会被直接操作,所以帧可以由堆(Heap)来分配。对于JVM 栈的内存不必是连续的。</p>
<p> JVM 规范允许JVM 栈的大小是固定的,也可以是根据需求计算来扩展和收缩。如果JVM 栈是固定大小,则每个JVM 栈大小可以在栈创建时独立地选择。一个JVM 实现可以让程序员或用户控制JVM 初始栈的大小,以及在动态扩展或收缩JVM 栈时,控制其最大值和最小值。</p>
<p>以下异常情况常与JVM 栈有关:</p>
<p>如果线程中的计算需要一个比允许的JVM 栈更大时,JVM 将会抛出StackOverflowError.</p>
<p>如果JVM 栈可动态扩展,当没有足够的内存分配给所尝试的扩展,或者没有足够的内存来为一个新线程创建初始化JVM 栈,JVM 将会抛出OutOfMemoryError.</p>
<blockquote>
<p><strong>堆(Heap)</strong></p>
</blockquote>
<p> JVM 有一个所有JVM 线程间共享的堆(Heap)。堆是分配所有类实例和数组内存的运行期数据区域。<br>堆在虚拟机启动时被创建。堆中对象的存储由自动存储管理系统(常被称为垃圾回收器或GC)回收,对象从来不会被显示的回收。JVM 承担着非特殊类型的自动存储管理系统,当然存储管理技术也可以根据实现者的系统要求来选择。堆可以是固定大小或是根据需求计算进行扩展,或者也可以是当一个大的堆不必要时进行收缩。堆的内存不需要是连续的。</p>
<p>一个JVM 实现可以让开发者或者用户控制堆初始的大小,同样的,如果堆能够动态扩展或者收缩,可以控制其最大值和最小值。</p>
<p>以下异常情况常与堆有关:如果计算需求所须更多的堆无法由自动存储管理系统提供时,JVM 将会抛出OutOfMemoryError.</p>
<blockquote>
<p><strong>方法区域(Method Area)</strong></p>
</blockquote>
<p>(1)方法区域存放了所加载的类的信息(名称、修饰符等)、类中的静态变量、类中定义为final类型的常量、类中的Field信息、类中的方法信息,当开发人员在程序中通过Class对象中的getName、isInterface等方法来获取信息时,这些数据都来源于方法区域,可见方法区域的重要性,同样,方法区域也是全局共享的,在一定的条件下它也会被GC;当方法区域需要使用的内存超过其允许的大小时,会抛出OutOfMemory的错误信息。</p>
<p>(2)方法区在虚拟机启动时被创建。虽然方法区逻辑上是堆的一部分,但是简单的实现可以选择既不垃圾回收也不压缩它。该版本的JVM 规范不要求指定方法区的位置或者用于管理编译后代码的策略。方法区可以是固定大小,也可以根据需求计算扩展,并且当大的方法区不再需要时进行收缩。方法区的内存不需要是连续的。 一个JVM 实现可以让开发者或用户控制方法区初始的大小,同样的,在可变大小方法区时,控制方法区的最大值和最小值。在Sun JDK中这块区域对应的为Permanet Generation,又称为持久代,默认为64M,可通过-XX:PermSize以及-XX:MaxPermSize来指定其大小。</p>
<blockquote>
<p><strong>运行时常量池(Runtime Constant Pool)</strong></p>
</blockquote>
<p>运行时常量池(Runtime Constant Pool)是方法区的一部分。Class文件中除了有类的版本、字段、方法、接口等描述信息外,还有一项信息是常量池(Constant Pool Table),用于存放编译期生成的各种字面量和符号引用,这部分内容将在类加载后进入方法区的运行时常量池中存放。</p>
<p>以下异常情况常与类或接口的常量池有关:当创建类或接口时,如果常量池的建立需要的内存不能被JVM 的方法区分配,JVM 会抛出OutOfMenoryError.</p>
<blockquote>
<p><strong>本地方法堆栈(Native Method Stacks)</strong></p>
</blockquote>
<p>本地方法栈(Native Method Stack)与虚拟机栈所发挥的作用是非常类似,它们之间的区别在于虚拟机栈为虚拟机执行Java方法服务,而本地方法栈则是为虚拟机使用到的Native方法服务。在虚拟机规范中对本地方法栈中方法使用的语言、使用方式与数据结构并没有强制规定,因此具体的虚拟机可以自由的实现它。</p>
<p>以下异常情况常与本地方法栈有关:</p>
<p>如果线程中计算所需的本地方法栈大于允许范围,JVM 会抛出StackOverflowError。</p>
<p>如果本地方法栈能动态扩展,当没有足够的内存分配给所尝试的扩展,或者没有足够的内存分配给新线程中创建的初始本地方法栈,JVM 就会抛出OutOfMemoryError。</p>
<p>与虚拟机栈一样,本地方法栈也是线程私有的。</p>
]]></content>
<summary type="html">
&lt;h2 id=&quot;1、什么是JVM&quot;&gt;&lt;a href=&quot;#1、什么是JVM&quot; class=&quot;headerlink&quot; title=&quot;1、什么是JVM&quot;&gt;&lt;/a&gt;1、什么是JVM&lt;/h2&gt;&lt;p&gt;JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。&lt;/p&gt;
&lt;p&gt;简单来说,JVM是用于执行Java应用程序和字节码的软件模块,并且可以将字节码转换为特定硬件和特定操作系统的本地代码。JVM在执行字节码时,实际上最终还是把字节码解释成具体平台上的机器指令执行,这就是Java的能够“一次编译,到处运行”的原因。&lt;/p&gt;
&lt;p&gt;JVM包括一套字节码指令集、一组寄存器、一个栈、一个垃圾回收堆和一个存储方法域。&lt;/p&gt;
&lt;h2 id=&quot;2、JRE-JDK-JVM是什么关系&quot;&gt;&lt;a href=&quot;#2、JRE-JDK-JVM是什么关系&quot; class=&quot;headerlink&quot; title=&quot;2、JRE/JDK/JVM是什么关系&quot;&gt;&lt;/a&gt;2、JRE/JDK/JVM是什么关系&lt;/h2&gt;&lt;p&gt;JRE(JavaRuntimeEnvironment,Java运行环境),也就是Java平台。所有的Java 程序都要在JRE下才能运行。普通用户只需要运行已开发好的java程序,安装JRE即可。&lt;/p&gt;
&lt;p&gt;JDK(Java Development Kit)是程序开发者用来来编译、调试java程序用的开发工具包。JDK的工具也是Java程序,也需要JRE才能运行。为了保持JDK的独立性和完整性,在JDK的安装过程中,JRE也是 安装的一部分。所以,在JDK的安装目录下有一个名为jre的目录,用于存放JRE文件。&lt;/p&gt;
&lt;p&gt;JVM(JavaVirtualMachine,Java虚拟机)是JRE的一部分。它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。JVM有自己完善的硬件架构,如处理器、堆栈、寄存器等,还具有相应的指令系统。Java语言最重要的特点就是跨平台运行。使用JVM就是为了支持与操作系统无关,实现跨平台。
</summary>
<category term="JVM" scheme="http://zhengweishan.oschina.io/categories/JVM/"/>
<category term="JAVA" scheme="http://zhengweishan.oschina.io/tags/JAVA/"/>
<category term="GC" scheme="http://zhengweishan.oschina.io/tags/GC/"/>
<category term="JVM" scheme="http://zhengweishan.oschina.io/tags/JVM/"/>
</entry>
</feed>
HTML
1
https://gitee.com/zhengweishan/zhengweishan.git
git@gitee.com:zhengweishan/zhengweishan.git
zhengweishan
zhengweishan
zhengweishan
master

搜索帮助