Jmeter源码学习系列:启动Jmeter

Jmeter源码学习系列:启动Jmeter

 

网上有很多Jmeter学习资料,但是源码这块,貌似资料不是很多,经历一番痛苦之后,决定自己一点点来做,希望能坚持,也希望能给后来的同学做点借鉴。

 

今天先简单看看jmeter是如何启动的

 

jmeter/src/core/org.apache.jmeter/NewDriver.Java是jmeter的总入口

/**
 * Main class for JMeter - sets up initial classpath and the loader.
 *
 */
public final class NewDriver {


先定义一些静态变量

private static final StringCLASSPATH_SEPARATOR= File.pathSeparator;

    private static final String OS_NAME=System.getProperty("os.name");// $NON-NLS-1$

    private static final StringOS_NAME_LC=OS_NAME.toLowerCase(java.util.Locale.ENGLISH);

    private static final String JAVA_CLASS_PATH= "java.class.path";//$NON-NLS-1$

    /** The classloader to use for loading JMeter classes. */
    privatestatic final DynamicClassLoaderloader;

    /** The directory JMeter isinstalled in. */
    privatestatic final StringJMETER_INSTALLATION_DIRECTORY;

    private static final List EXCEPTIONS_IN_INIT=new ArrayList<>();

    static {
        finalList jars =new LinkedList<>();
        final String initial_classpath = System.getProperty(JAVA_CLASS_PATH);




寻找Jmeter的安装目录,这边对Mac OS的Jmeter做了特殊处理
       

 // Find JMeter home dir from the initial classpath
        String tmpDir=null;
        StringTokenizer tok = newStringTokenizer(initial_classpath,File.pathSeparator);
        if (tok.countTokens() == 1
                || (tok.countTokens() == 2 // Java on Mac OS can add a second entry to theinitial classpath
                    && OS_NAME_LC.startsWith("mac os x")//$NON-NLS-1$
                   )
           ) {
            File jar = new File(tok.nextToken());
            try {
                tmpDir =jar.getCanonicalFile().getParentFile().getParent();
            } catch(IOException e) {
            }
        } else {// e.g. started from IDE with full classpath
            tmpDir = System.getProperty("jmeter.home","");// Allow override $NON-NLS-1$ $NON-NLS-2$
            if (tmpDir.length()==0) {
                File userDir = new File(System.getProperty("user.dir"));// $NON-NLS-1$
                tmpDir = userDir.getAbsoluteFile().getParent();
            }
        }
        JMETER_INSTALLATION_DIRECTORY=tmpDir;

        /*
         * Does the system support UNCpaths? If so, may need to fix them up
         * later
         */
        boolean usesUNC=OS_NAME_LC.startsWith("windows");// $NON-NLS-1$



找到安装目录之后,对Jmeter lib目录下的jar包进行扫描,并使用DynamicClassLoader进行加载
    

    // Addstandard jar locations to initial classpath
        StringBuilderclasspath = newStringBuilder();
        File[]libDirs = newFile[] { newFile(JMETER_INSTALLATION_DIRECTORY+ File.separator+"lib"),// $NON-NLS-1$ $NON-NLS-2$
                new File(JMETER_INSTALLATION_DIRECTORY+ File.separator+ "lib" + File.separator + "ext"),// $NON-NLS-1$ $NON-NLS-2$
                new File(JMETER_INSTALLATION_DIRECTORY+ File.separator+ "lib" + File.separator + "junit")};// $NON-NLS-1$ $NON-NLS-2$
        for(File libDir : libDirs) {
            File[] libJars =libDir.listFiles((FilenameFilter) (dir,name) -> name.endsWith(".jar"));
            if (libJars == null) {
                new Throwable("Could not access "+ libDir).printStackTrace();// NOSONAR No logging here
                continue;
            }
            Arrays.sort(libJars); // Bug 50708 Ensurepredictable order of jars
            for (File libJar :libJars) {
                try {
                    String s =libJar.getPath();

                    //Fix path to allow the use of UNC URLs
                    if (usesUNC) {
                        if (s.startsWith("\\\\") &&!s.startsWith("\\\\\\")) {// $NON-NLS-1$$NON-NLS-2$
                            s = "\\\\"+ s;// $NON-NLS-1$
                        } else if(s.startsWith("//") && !s.startsWith("///")) {// $NON-NLS-1$ $NON-NLS-2$
                            s = "//"+ s;// $NON-NLS-1$
                        }
                    } // usesUNC

                    jars.add(newFile(s).toURI().toURL());// See Java bug 4496398
                    classpath.append(CLASSPATH_SEPARATOR);
                    classpath.append(s);
                } catch(MalformedURLException e) { // NOSONAR
                    EXCEPTIONS_IN_INIT.add(newException("Error adding jar:"+libJar.getAbsolutePath(),e));
                }
            }
        }

        //ClassFinder needs the classpath
        System.setProperty(JAVA_CLASS_PATH,initial_classpath + classpath.toString());
        loader= AccessController.doPrivileged(
                new java.security.PrivilegedAction(){
                    @Override
                    public DynamicClassLoaderrun() {
                        return new DynamicClassLoader(jars.toArray(newURL[jars.size()]));
                    }
                }
        );
    }


运行Jmeter的主方法
  

  /**
     * The main program which actuallyruns JMeter.
     *
     * @param args
     *            the command line arguments
     */
    publicstatic void main(String[] args) {
        if(!EXCEPTIONS_IN_INIT.isEmpty()) {
            System.err.println("Configuration error during init, see exceptions:"+exceptionsToString(EXCEPTIONS_IN_INIT));
        }else {
            Thread.currentThread().setContextClassLoader(loader);

            setLoggingProperties(args);

            try {
                ClassinitialClass = loader.loadClass("org.apache.jmeter.JMeter");// $NON-NLS-1$
                Object instance = initialClass.newInstance();
                Method startup = initialClass.getMethod("start", newClass[] { newString[0].getClass() });// $NON-NLS-1$
                startup.invoke(instance,new Object[] { args });
            } catch(Throwable e){ // NOSONARWe want to log home directory in case of exception
                e.printStackTrace(); // NOSONAR No logger at this step
                System.err.println("JMeterhome directory was detected as: "+JMETER_INSTALLATION_DIRECTORY);
            }
        }
    }


还有一部分静态方法,就不贴了

你可能感兴趣的:(jmeter)