Tải bản đầy đủ - 0 (trang)
Chapter 16. Load and Performance Testing with JMeter

Chapter 16. Load and Performance Testing with JMeter

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

100concurrentusers,thehomepagemustbedisplayedin

fewerthan2secondsonabroadbandconnection.

JMetercanbeusedveryeffectivelytodobothloadand

performancetesting.

Beforewestart,awordonloadtesting:aswithanyothersort

ofperformancetestingandoptimization,toloadtestyour

applicationwell,youreallyneedaplan.Howmanyusersisyour

applicationsupposedtosupport?Areyouwritingacompany

applicationforlimitedinternaluse,orareyouworkingonthe

newreleaseofAmazon.com?Whatsortofresponsetimesare

acceptable,andunderwhatload?

Don'tneglectenvironmentalissues,either.Isthetestserver

(you'renotrunningyourloadtestsonyourproductionserver,

areyounow?)similarinsizeandgruntpowertotheproduction

server?Whatotherapplicationswillberunningonthe

productionserver?Howmuchmemorywillbeavailabletoyour

applicationinproduction?

Thesethingsshouldbethoughtthroughwitheveryoneinvolved

intheproject(don'tforgetthesystemguys!),writtendownfor

alltosee,andusedtobuildatleastabasicload-testplan.



Chapter16.LoadandPerformance

TestingwithJMeter

Introduction

InstallingJMeter

TestingaSimpleWebApplication

StructuringYourTestCase

RecordingandDisplayingTestResults

UsingtheJMeterProxytoRecordaTestCase

TestingUsingVariables

TestingonMultipleMachines



16.1.Introduction

JMeterisapowerfulJavaopensourceloadandperformance

testingtool.Withit,youcancarryoutperformancetestson

webapplication,databases,webservices,andmore.

Loadtesting(alsoknownasstresstesting)involvesputting

yourapplicationundercontinuedstressoveralongperiodof

time,generallybysimulatingmanyconcurrentusers.Thisisa

goodwayofferretingoutmemoryleaksorperformance

bottlenecksthatotherwisewouldnotappearuntiloncethe

applicationisinproduction.Loadtestingcanalsobeusedto

pushanapplicationtoitslimits,simulatingexpectedpeak

loads,inordertostudyhowitstandsupunderincreasing

pressureandtoidentifyweakpointsintheapplication

architecture.

PerformanceTestingisalittledifferent.Performancetesting

involvesmakingsurethatyourapplicationperformsasspecified

inthesystemrequirements.Forexample,therequirements

mayincludeperformancecriteriasuchasthefollowing:with



100concurrentusers,thehomepagemustbedisplayedin

fewerthan2secondsonabroadbandconnection.

JMetercanbeusedveryeffectivelytodobothloadand

performancetesting.

Beforewestart,awordonloadtesting:aswithanyothersort

ofperformancetestingandoptimization,toloadtestyour

applicationwell,youreallyneedaplan.Howmanyusersisyour

applicationsupposedtosupport?Areyouwritingacompany

applicationforlimitedinternaluse,orareyouworkingonthe

newreleaseofAmazon.com?Whatsortofresponsetimesare

acceptable,andunderwhatload?

Don'tneglectenvironmentalissues,either.Isthetestserver

(you'renotrunningyourloadtestsonyourproductionserver,

areyounow?)similarinsizeandgruntpowertotheproduction

server?Whatotherapplicationswillberunningonthe

productionserver?Howmuchmemorywillbeavailabletoyour

applicationinproduction?

Thesethingsshouldbethoughtthroughwitheveryoneinvolved

intheproject(don'tforgetthesystemguys!),writtendownfor

alltosee,andusedtobuildatleastabasicload-testplan.



16.2.InstallingJMeter

InstallingJMeterisstraightforward.Inthetraditionofmany

opensourcetools,therearenofancyinstallers.Justdownload

thelatestversionfromtheJMeterwebsite[61](version2.2at

thetimeofthiswriting),andextractthepackageintoa

directoryofyourchoice.Youwillfindstartupscriptsfor

Windows(jmeter.bat)andUnix(jmeter)tostartJMeterinthe

binsubdirectory.YouneedtostartJMeterinthisdirectory.For

example,ifyouhadextractedtheJMeter2.3distributioninto

theD:\tools\jmeterdirectoryonaWindowsmachine,youcould

runJMeterasfollows:

D:>cdD:\tools\jmeter\jakarta-jmeter-2.3\bin

D:\tools\jmeter\jakarta-jmeter-2.3\bin>jmeter.bat

Or,onaUnixbox,withJMeterinstalledintothe

/usr/local/jmeterdirectory,youwoulddothefollowing:

$cd/usr/local/jmeter/jakarta-jmeter-2.3/bin

$jmeter

RunningthiscommandwillstartuptheJMetergraphical

console,whichiswereyouwriteyourtestscripts(called"Test

Plans"inJMeterparlance),runyourtests,andviewtheresults.

[61]http://jakarta.apache.org/jmeter/



Dependingonthetypeoftestsyouintendtodo,youmayneed

toprovideJMeterwithsomeadditionalJARfiles.Thesimplest

waytodothisistoplacetheminthelibdirectory,wherethey

willbedetectedautomaticallybytheJMeterstartupscript.For

example,ifyouintendtodoanyJDBCtesting,youwillneedto

supplytheJDBCdrivers,orifyouaretestingwebservices,you

mayneedtoaddthemail.jarandactivation.jarfiles.



16.3.TestingaSimpleWebApplication

Now,wewillgothoughthestepsinvolvedincreatingatypical

testplanforawebapplication.Thetestplanwillrunasimple

webapplicationthroughitspaces,simulatingtheexpectedload

of100concurrentusers.Ourspecificationsstipulatethatwith

100concurrentusers,theaverageresponsetimemustbefewer

than2secondsperpage.



16.3.1.SettingUpaThreadGroup

JMeterworksbysimulatingasetofconcurrentusers

performingvarioustasksonyourapplication.InJMeter,youuse

athreadgrouptomanagethissetofusers.Asthename

suggests,athreadgroupdefinesagroupofthreads.Each

simulateduserisrepresentedbyaseparatethread.Sothe

numberofthreadsrepresentsthenumberofsimulated

simultaneoususersgeneratedbythisThreadGroup.Tocreatea

newthreadgroup,justselectEdit Add ThreadGroupinthe

mainmenu,orplacethecursorontheTestPlanentryanduse

thecontextualmenu(seeFigure16-1).

Figure16-1.Creatinganewthreadgroup



ThemostimportantfieldintheThreadGroupdetailsscreen

(seeFigure16-2)isthenumberofusers,whichyoudefinein

the"NumberofThreads"field.

Tosimulateloadmorerealistically,thethreads(think"users")

arenotstartedallatonce—thereisashortdelaybetween

startingeachthread.Thisspreadstherequestsovertimeand

makesformorerealistictesting.Thetotaltimespentstarting

thethreadsiscalledtheRampUpPeriod.So,ifyouhavea

threadgroupwith100threadsandarampupperiodof3,000

seconds,anewthreadwillbestartedevery30seconds.



16.3.2.SchedulingYourTests

Thereareseveralwaystodefinehowlongyouwantyourtests

torun.Themostsimple,andarguablytheleastuseful,isto

definethenumberoftimesthatthetestcaseshouldbe

executed,ortosimplyleavetheteststorunforeverandstop

thetestprocessmanually.Inpractice,itisdifficulttoestimate

howlongthetestplanwilltaketorun,especiallyina

concurrentenvironment.Inaddition,afterrunningforalong

period,JMetercanbecomesluggish,makingitmoredifficultto

stopthetestprocessmanually.

TheotherpossibilityistousetheScheduler,whichallowsyouto

scheduleyourloadtestsforsomepointinthefuture.Youcan

specifyastartandendtimeforyourtests,usefulifyouwantto

runyourtestsoutsideworkinghours,forexample.

Alternatively,asshownintheillustration,youcanspecifya

fixedduration(theEndTimefieldisignoredinthiscase).You

mayalsowanttoscheduletheteststostartafteracertain

delay(say,inanhour'stime),byprovidingavalueinthe

StartupDelayfield.Inthiscase,theStartTimewillbeignored.

Figure16-2.TheThreadGroup



16.3.3.SettingUptheHTTPRequest

ConfigurationElements

Configurationtestsscriptscanberepetitive.Whentestinga

website,forexample,alloftheHTTPrequestswilltypicallybe

senttothesameserver.InJMeter,youcanuseConfiguration

Elementstofactorizealotofthisrepeateddataintoonecentral

location.IfsomepagesareprotectedusingBasicHTTP

Authentication(otherformsofauthenticationarenotcurrently

supported),user/passworddatacanbeshared.Andifyourweb

applicationusescookiestomanagesessions,JMetercanstore

thesecookieswhentheyarereceivedandmakethemavailable

toallsubsequentrequests.

Forwebapplicationtesting,themostimportantconfiguration

elementis"HTTPRequestDefaults."Addonetoyourtestplan

byclickingonTestPlanandselectingAdd ConfigElement



HTTPRequestDefaultsinthecontextualmenu.Youcanspecify

thenameofyourtestserver,theportyourwebapplicationis

runningon,theprotocol(HTTPorHTTPS),andtheapplication

contextpath.ThesevalueswillbeusedbytheHTTPRequests

thatyouwillsetuplateron.

Throughouttherestofthischapter,wewillbeperformingsome

loadtestingononeoftheopensourceimplementationsofthe

JavaPetStore.referenceapplication.[*]InFigure16-3,weset

upthedefaultdataforourtestplatform,whichisrunningona

localtestservercalledtestserver,onthe8080port.Thiswillbe

usedbydefaultforalltheHTTPrequestsinthistestplan.

[*]Thejpetstoreimplementation,writtenbytheIBATISteam



Ifyoucheckthe"RetrieveAllEmbeddedResourcesfromHTML

Files"option,JMeterwilldownloadtheimages,Javacriptfiles,

CSSstylesheets,andsoonassociatedwithanHTTPrequest.

However,JMeterdoesnotcacheimagesanddownloadedfilesas

abrowserdoes,soitisgenerallynotagoodideatoactivate

thisoptionintherequestdefaultsandonlyactivateitin

selectedHTTPrequests.

Figure16-3.TheHTTPRequestDefaults



AnotherveryusefulconfigurationelementistheHTTPcookie

manager.Thecookiemanagerstorescookiesandmakesthem



availableforsubsequentrequeststothesamesite,asan

ordinarywebbrowserwould.Becauseeachthreadrepresentsa

differentuser,cookiesarenotsharedamongthreads.

IfsomeorallofyoursiteisprotectedbybasicHTTP

authentication,youcanprovideusernamesandpasswordsin

theHTTPauthorizationmanager.BasicHTTPauthenticationis

thesimplestofthestandardHTTPauthenticationmethods:

whenausernavigatestoapageprotectedbybasicHTTP

authentication,thebrowserwillopenadialogboxpromptingfor

ausernameandpassword.JMeterletsyousetupusernames

andpasswordsforoneormoreURLpathsinyourapplication.

OtherHTTPauthenticationmethods,suchasthemoresecure

digestauthentication,arenotsupported.NotethatJMeterdoes

supportSSLconnections,whichisconsideredtobethemost

reliablewaytosecureawebapplication.



16.3.4.AddinganHTTPRequest

JMetertestsawebsitebysendingHTTPrequeststotheserver,

simulatingtheactionofrealusers.TheseHTTPrequestsare

builtusingsamplers.Samplersarethebasicbuildingblocksof

allJMetertestplans,andcomeinavarietyofdifferentshapes

andcolors.InadditiontoHTTPrequestsamplers,youcanalso

buildsamplersforFTPrequests,webservicerequests,JMS

messages,JDBCqueries,andmanyothers.Whenyouare

testingawebsite,however,theHTTPsamplerisbyfarthe

mostcommonlyused.

Thewebapplicationwearetestingisanopensource

implementationoftheJPetstoredemoapplicationfromiBatis

(seeFigure16-4).Ifyouwanttofollowalongwiththe

examples,youcandownloadfromtheIBatiswebsite.[*]Thisis

actuallyoflittleimportance,asyoucanuseJMetertotestjust

aboutanywebsiteyoulike,andthetechniquesaresimilarfor

mostsites.However,knowingwhatwearetestingwillmakeit

easiertounderstandtheexamples.

Figure16-4.TheJPetstoreapplication



CreatinganewHTTPRequestsamplerisstraightforward,

althoughitcanbealittlelaboriousiftherearealotof

parameters.Typically,youwouldstartoffwitharequestforthe

homepage.Althoughyoudon'tneedtounderstandallthe

nitty-grittyarchitecturaldetailsoftheapplicationyouare

testing,youdoneedtoknowwhattherequestyouwantto

sendissupposedtolooklike.Usually,themostpracticalwayto

dothisistoperformtheactionyourselfinawebbrowserand

lookattheURL.Inthiscase,thehomepageURLlookslike

http://testserver:8080/jpetstore/shop/index.shtml.

[*]http://ibatis.apache.org/javadownloads.cgi



ThisisallweneedtosetupaJMeterHTTPsampler.Addan

HTTPRequestsamplertoyourtestplanusingAdd Sampler

HTTPRequest(seeFigure16-5).Changethenameto

somethingmeaningful,sothatyouwillbeabletoidentifythis

requesteasilyinthetestplan.YoucanleavetheWebServer

detailsempty;theywillberetrievedfromtheHTTPdefault

valueswesetupearlier.Theonlyvalueweneedtoprovideis

thewebpage,independentoftheapplicationcontext.Inthis

case,thiswouldbe"/index.shtml."



Asdiscussedabove,youcanalsochoosetoretrieveembedded

resourcessuchasimages,javascriptfiles,andcssstylesheets.

Forarealuser,thehomepageusuallyhasalotofimagesand

resourcesthatwillbefetchedhereandcachedbythebrowser,

soit'softenagoodideatoretrievethesethefirsttimeyou

fetchthehomepageinyourtestplan.

Figure16-5.Queryingthehomepage



Next,we'llbuildanHTTPrequesttotakeusintotheReptiles

sectionofthecatalog.TheURLforthispagelookslike

http://testserver:8080/jpetstore/shop/viewCategory.shtml?

categoryId=REPTILES.

NowwecansetupaJMeterHTTPsamplerforthisquery(see

Figure16-6).AddanHTTPRequestsamplertoyourtestplan

usingAdd Sampler HTTPRequest(seeFigure16-6),and

giveitsomeappropriatename("Reptilecatalog,"forexample).

ThenprovidethePathvalue,whichisthepathtothispageon

theserver,withoutanyparameters.Inthiscase,itisthe



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

Chapter 16. Load and Performance Testing with JMeter

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

×