JMeter Java Code Performance test

Source: Internet
Author: User

first, the environment preparation1. Create a new Java Project 2, import jar package: Apachejmeter_core.jar Apachejmeter_java.jar These two jars are the most basic jar using JMeter, allowing your code Run in JMeter, if you need additional jars during code writing, import them yourself. second, the code should know before writing         1, if you want your code to run in JMeter, When creating classes, you need to inherit abstractjavasamplerclient abstract classes or implement Javasamplerclient interfaces              Abstractjavasamplerclient Abstract class is a subclass of the Javasamplerclient interface, and when you do not need to replicate all the required methods of replication, then you only need to inherit the Abstractjavasamplerclient abstract class.              If you choose to implement the Javasamplerclient interface, then you need to make a carbon copy of the method:        & nbsp                public sampleresult runtest (javasamplercontext context) {}  &N Bsp                      public void Setuptest (Javasamplercontext conte XT) {}                         public void Teardowntest (J Avasamplercontext context) {}                         pub Lic Arguments getdefaultparameters () {}            These 4 methods must be replicated, but if you choose to inherit ABSTractjavasamplerclient this abstract class, you only need to replicate the methods you need.          2, method description:                    public Arguments getdefaultparameters () {}                        &N Bsp   This method is the first run by JMeter when you add Javarequest, which determines which properties you want to display by default in the GUI.                     public void Setuptest (Javasamplercontext contex T {}                            This method is equivalent to the LoadRunner Init, we can use it to perform some initialization actions.                     public Sampleresult runtest (javasamplercontext Context) {}                            This method is equivalent to Loadr The action in Unner, our core test code is here.                     public void Teardowntest (JavasaMplercontext context) {}                            This method is equivalent to the end in LoadRunner, and the finishing touches can be done by it.          3, in addition to the above 2 points, we generally need to implement serializable, serialization of the tag interface, so that our class can be serialized.   Three, code writing
Package Com.lingfeng.jmeter.practice;import Java.io.ioexception;import Java.io.inputstream;import Java.io.serializable;import Java.net.malformedurlexception;import Java.net.url;import java.net.URLConnection; Import Org.apache.jmeter.config.arguments;import Org.apache.jmeter.protocol.java.sampler.abstractjavasamplerclient;import Org.apache.jmeter.protocol.java.sampler.javasamplercontext;import Org.apache.jmeter.samplers.SampleResult; public class Myjavarequest extends Abstractjavasamplerclient implements Serializable {private static final long Serialver Sionuid = 1l;private String surl;//stores the Urlprivate static final String url_name= "URL" of the user output;//sets the name of the variable that the GUI page displays// Set GUI page default display variable value, the default is to visit Baidu private static final String urlvalue_default= "http://www.baidu.com";// The Resultdata variable is used to store the response data in order to be displayed in the view results tree.    Private String Resultdata; StringBuilder sbresultdata = new StringBuilder ();/* This method is used to control the properties displayed on the GUI page and is set by the user. * This method is not called, it is a life-cycle related method, and the class load is run. * (non-javadoc) * @see Org.apache.jmeter.protocol.java.samplEr. Abstractjavasamplerclient#getdefaultparameters () */@Overridepublic Arguments getdefaultparameters () {Arguments arguments = new arguments (); Arguments.addargument (Url_name, string.valueof (Urlvalue_default)); return arguments;} @Overridepublic void Setuptest (Javasamplercontext context) {sURL = Context.getparameter (Url_name, Urlvalue_default); if (Surl.length () ==0) {surl= "http://www.baidu.com";//If the user does not set the URL, then let him visit Baidu, haha.        }} @Override public Sampleresult runtest (Javasamplercontext context) {/* * Sampleresult This class is used to output test results to the view results tree.      * and is also used to control the start and end of transactions.        */Sampleresult results = new Sampleresult (); Results.setsamplelabel ("Test" +surl+ "website access speed AH!!        "); Try{url url = new URL (surl);            URLConnection conn = Url.openconnection (); InputStream in = Conn.getinputstream (); byte[] buffer = new Byte[1024];int len; The transaction starts with the tag Results.samplestart (), while ((Len=in.read (buffer))!=-1) {resultdata = new String (buffer, "UTF-8");//will read every The page return information is stored in the Resultdata sbresultdata.append (reSultdata);//Every time you read it, add it to SB.                } in.close (); }catch (malformedurlexception e) {results.setsuccessful (false); E.printstacktrace ();} catch (IOException e) {results.setsuccessful (false); E.printstacktrace ();}        catch (Exception e) {//If an exception occurs, the message is snapped, and the transaction fails to send.        Results.setsuccessful (FALSE);        E.printstacktrace ();        }finally{//Mark Transaction End Results.sampleend (); } results.setsuccessful (true); resultdata = Sbresultdata.tostring ();//converts all read data to a string Results.setresponsedata (        Resultdata,null);//print data to view results Tree Results.setdatatype (sampleresult.text);    return results; }}

iv. JMeter running Java code1. Package the code into Jar 2, put the packaged jar under the \apache-jmeter-2.12\lib\ext path 3, open the JMeter GUI, add a thread group, add a Java request, such as: 4, add view result tree , the following results are run: v. Supplementary MattersWhen our code runs, it will be printed in the Doc window and I don't have an exception, so there is no data and it will print here when an exception occurs. Watch out and help debug your code Six, the last words   In fact, from the above code can be seen, this section of the test code is actually not much testing significance, is to simulate an HTTP request to visit a website.    But when we need to perform a performance test of a piece of code so that we can write it, and then make a call in the Runtest method, it's time to test the performance of the code. Often summarize, learn from each other!!

JMeter Java Code Performance test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.