`
zhangyu84849467
  • 浏览: 15407 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

ActiveMQ 启动时broker 的源代码调试

 
阅读更多

 

入口在 org.apache.activemq.console.Main这个类

 

在main方法内最前面加入如下代码

 

// debug

System.setProperty("activemq.base", "E:\\apache-activemq-5.10.2");

System.setProperty("activemq.home", "E:\\apache-activemq-5.10.2");

System.setProperty("org.apache.activemq.default.directory.prefix", "E:\\activeMQ\\");

 

eclipse 中 program arguments 如下

 

start broker:(tcp://localhost:61616)?brokerName=broker&deleteAllMessagesOnStartup=true

 

截图如下



 

 

具体 URL 后的参数在这里  http://activemq.apache.org/broker-uri.html

 

 



 

 

 

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activemq.console;

import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * Main class that can bootstrap an ActiveMQ broker console. Handles command
 * line argument parsing to set up and run broker tasks.
 */
public class Main {

    public static final String TASK_DEFAULT_CLASS = "org.apache.activemq.console.command.ShellCommand";
    private static boolean useDefExt = true;

    private File activeMQHome;
    private File activeMQBase;
    private ClassLoader classLoader;
    private final Set<File> extensions = new LinkedHashSet<File>();
    private final Set<File> activeMQClassPath = new LinkedHashSet<File>();

    public static void main(String[] args) {
    	// debug
    	System.setProperty("activemq.base", "E:\\apache-activemq-5.10.2");
    	System.setProperty("activemq.home", "E:\\apache-activemq-5.10.2");
    	System.setProperty("org.apache.activemq.default.directory.prefix", "E:\\activeMQ\\");
    	
        // Create the tmpdir if it does not exist yet..
        File tmpdir = new File(System.getProperty("java.io.tmpdir"));
        if(!tmpdir.exists()) {
            tmpdir.mkdirs();
        }

        Main app = new Main();

        // Convert arguments to collection for easier management
        List<String> tokens = new LinkedList<String>(Arrays.asList(args));
        // Parse for extension directory option
        app.parseExtensions(tokens);

        // lets add the conf directory first, to find the log4j.properties just in case its not
        // in the activemq.classpath system property or some jar incorrectly includes one
        File confDir = app.getActiveMQConfig();
        app.addClassPath(confDir);

        // Add the following to the classpath:
        //
        // ${activemq.base}/conf
        // ${activemq.base}/lib/* (only if activemq.base != activemq.home)
        // ${activemq.home}/lib/*
        // ${activemq.base}/lib/optional/* (only if activemq.base != activemq.home)
        // ${activemq.home}/lib/optional/*
        // ${activemq.base}/lib/web/* (only if activemq.base != activemq.home)
        // ${activemq.home}/lib/web/*

        if (useDefExt && app.canUseExtdir()) {

            boolean baseIsHome = app.getActiveMQBase().equals(app.getActiveMQHome());

            File baseLibDir = new File(app.getActiveMQBase(), "lib");
            File homeLibDir = new File(app.getActiveMQHome(), "lib");

            if (!baseIsHome) {
                app.addExtensionDirectory(baseLibDir);
            }
            app.addExtensionDirectory(homeLibDir);

            if (!baseIsHome) {
                app.addExtensionDirectory(new File(baseLibDir, "camel"));
                app.addExtensionDirectory(new File(baseLibDir, "optional"));
                app.addExtensionDirectory(new File(baseLibDir, "web"));
                app.addExtensionDirectory(new File(baseLibDir, "extra"));
            }
            app.addExtensionDirectory(new File(homeLibDir, "camel"));
            app.addExtensionDirectory(new File(homeLibDir, "optional"));
            app.addExtensionDirectory(new File(homeLibDir, "web"));
            app.addExtensionDirectory(new File(homeLibDir, "extra"));
        }

        // Add any custom classpath specified from the system property activemq.classpath
        app.addClassPathList(System.getProperty("activemq.classpath"));

        try {
            app.runTaskClass(tokens);
            System.exit(0);
        } catch (ClassNotFoundException e) {
            System.out.println("Could not load class: " + e.getMessage());
            try {
                ClassLoader cl = app.getClassLoader();
                if (cl != null) {
                    System.out.println("Class loader setup: ");
                    printClassLoaderTree(cl);
                }
            } catch (MalformedURLException e1) {
            }
            System.exit(1);
        } catch (Throwable e) {
            System.out.println("Failed to execute main task. Reason: " + e);
            System.exit(1);
        }
    }

    /**
     * Print out what's in the classloader tree being used.
     *
     * @param cl
     * @return depth
     */
    private static int printClassLoaderTree(ClassLoader cl) {
        int depth = 0;
        if (cl.getParent() != null) {
            depth = printClassLoaderTree(cl.getParent()) + 1;
        }

        StringBuffer indent = new StringBuffer();
        for (int i = 0; i < depth; i++) {
            indent.append("  ");
        }

        if (cl instanceof URLClassLoader) {
            URLClassLoader ucl = (URLClassLoader)cl;
            System.out.println(indent + cl.getClass().getName() + " {");
            URL[] urls = ucl.getURLs();
            for (int i = 0; i < urls.length; i++) {
                System.out.println(indent + "  " + urls[i]);
            }
            System.out.println(indent + "}");
        } else {
            System.out.println(indent + cl.getClass().getName());
        }
        return depth;
    }

    public void parseExtensions(List<String> tokens) {
        if (tokens.isEmpty()) {
            return;
        }

        int count = tokens.size();
        int i = 0;

        // Parse for all --extdir and --noDefExt options
        while (i < count) {
            String token = tokens.get(i);
            // If token is an extension dir option
            if (token.equals("--extdir")) {
                // Process token
                count--;
                tokens.remove(i);

                // If no extension directory is specified, or next token is
                // another option
                if (i >= count || tokens.get(i).startsWith("-")) {
                    System.out.println("Extension directory not specified.");
                    System.out.println("Ignoring extension directory option.");
                    continue;
                }

                // Process extension dir token
                count--;
                File extDir = new File(tokens.remove(i));

                if (!canUseExtdir()) {
                    System.out.println("Extension directory feature not available due to the system classpath being able to load: " + TASK_DEFAULT_CLASS);
                    System.out.println("Ignoring extension directory option.");
                    continue;
                }

                if (!extDir.isDirectory()) {
                    System.out.println("Extension directory specified is not valid directory: " + extDir);
                    System.out.println("Ignoring extension directory option.");
                    continue;
                }

                addExtensionDirectory(extDir);
            } else if (token.equals("--noDefExt")) { // If token is
                // --noDefExt option
                count--;
                tokens.remove(i);
                useDefExt = false;
            } else {
                i++;
            }
        }

    }

    public void runTaskClass(List<String> tokens) throws Throwable {

        StringBuilder buffer = new StringBuilder();
        buffer.append(System.getProperty("java.vendor"));
        buffer.append(" ");
        buffer.append(System.getProperty("java.version"));
        buffer.append(" ");
        buffer.append(System.getProperty("java.home"));
        System.out.println("Java Runtime: " + buffer.toString());

        buffer = new StringBuilder();
        buffer.append("current=");
        buffer.append(Runtime.getRuntime().totalMemory()/1024L);
        buffer.append("k  free=");
        buffer.append(Runtime.getRuntime().freeMemory()/1024L);
        buffer.append("k  max=");
        buffer.append(Runtime.getRuntime().maxMemory()/1024L);
        buffer.append("k");
        System.out.println("  Heap sizes: " + buffer.toString());

        List<?> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
        buffer = new StringBuilder();
        for (Object arg : jvmArgs) {
            buffer.append(" ").append(arg);
        }
        System.out.println("    JVM args:" + buffer.toString());
        System.out.println("Extensions classpath:\n  " + getExtensionDirForLogging());
        System.out.println("ACTIVEMQ_HOME: " + getActiveMQHome());
        System.out.println("ACTIVEMQ_BASE: " + getActiveMQBase());
        System.out.println("ACTIVEMQ_CONF: " + getActiveMQConfig());
        System.out.println("ACTIVEMQ_DATA: " + getActiveMQDataDir());

        ClassLoader cl = getClassLoader();
        Thread.currentThread().setContextClassLoader(cl);

        // Use reflection to run the task.
        try {
            String[] args = tokens.toArray(new String[tokens.size()]);
            Class<?> task = cl.loadClass(TASK_DEFAULT_CLASS);
            Method runTask = task.getMethod("main", new Class[] {
                String[].class, InputStream.class, PrintStream.class
            });
            runTask.invoke(task.newInstance(), args, System.in, System.out);
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    }

    public void addExtensionDirectory(File directory) {
        extensions.add(directory);
    }

    public void addClassPathList(String fileList) {
        if (fileList != null && fileList.length() > 0) {
            StringTokenizer tokenizer = new StringTokenizer(fileList, ";");
            while (tokenizer.hasMoreTokens()) {
                addClassPath(new File(tokenizer.nextToken()));
            }
        }
    }

    public void addClassPath(File classpath) {
        activeMQClassPath.add(classpath);
    }

    /**
     * The extension directory feature will not work if the broker factory is
     * already in the classpath since we have to load him from a child
     * ClassLoader we build for it to work correctly.
     *
     * @return true, if extension dir can be used. false otherwise.
     */
    public boolean canUseExtdir() {
        try {
            Main.class.getClassLoader().loadClass(TASK_DEFAULT_CLASS);// org.apache.activemq.console.command.ShellCommand
            return false;
        } catch (ClassNotFoundException e) {
            return true;
        }
    }

    public ClassLoader getClassLoader() throws MalformedURLException {
        if (classLoader == null) {
            // Setup the ClassLoader
            classLoader = Main.class.getClassLoader();
            if (!extensions.isEmpty() || !activeMQClassPath.isEmpty()) {

                ArrayList<URL> urls = new ArrayList<URL>();

                for (Iterator<File> iter = activeMQClassPath.iterator(); iter.hasNext();) {
                    File dir = iter.next();
                    urls.add(dir.toURI().toURL());
                }

                for (Iterator<File> iter = extensions.iterator(); iter.hasNext();) {
                    File dir = iter.next();
                    if (dir.isDirectory()) {
                        File[] files = dir.listFiles();
                        if (files != null) {

                            // Sort the jars so that classpath built is consistently in the same
                            // order. Also allows us to use jar names to control classpath order.
                            Arrays.sort(files, new Comparator<File>() {
                                public int compare(File f1, File f2) {
                                    return f1.getName().compareTo(f2.getName());
                                }
                            });

                            for (int j = 0; j < files.length; j++) {
                                if (files[j].getName().endsWith(".zip") || files[j].getName().endsWith(".jar")) {
                                    urls.add(files[j].toURI().toURL());
                                }
                            }
                        }
                    }
                }

                URL u[] = new URL[urls.size()];
                urls.toArray(u);
                classLoader = new URLClassLoader(u, classLoader);
            }
            Thread.currentThread().setContextClassLoader(classLoader);
        }
        return classLoader;
    }

    public void setActiveMQHome(File activeMQHome) {
        this.activeMQHome = activeMQHome;
    }

    public File getActiveMQHome() {
        if (activeMQHome == null) {
            if (System.getProperty("activemq.home") != null) {
                activeMQHome = new File(System.getProperty("activemq.home"));
            }

            if (activeMQHome == null) {
                // guess from the location of the jar
                URL url = Main.class.getClassLoader().getResource("org/apache/activemq/console/Main.class");
                if (url != null) {
                    try {
                        JarURLConnection jarConnection = (JarURLConnection)url.openConnection();
                        url = jarConnection.getJarFileURL();
                        URI baseURI = new URI(url.toString()).resolve("..");
                        activeMQHome = new File(baseURI).getCanonicalFile();
                        System.setProperty("activemq.home", activeMQHome.getAbsolutePath());
                    } catch (Exception ignored) {
                    }
                }
            }

            if (activeMQHome == null) {
                activeMQHome = new File("../.");
                System.setProperty("activemq.home", activeMQHome.getAbsolutePath());
            }
        }

        return activeMQHome;
    }

    public File getActiveMQBase() {
        if (activeMQBase == null) {
            if (System.getProperty("activemq.base") != null) {
                activeMQBase = new File(System.getProperty("activemq.base"));
            }

            if (activeMQBase == null) {
                activeMQBase = getActiveMQHome();
                System.setProperty("activemq.base", activeMQBase.getAbsolutePath());
            }
        }

        return activeMQBase;
    }

    public File getActiveMQConfig() {
        File activeMQConfig = null;

        if (System.getProperty("activemq.conf") != null) {
            activeMQConfig = new File(System.getProperty("activemq.conf"));
        } else {
            activeMQConfig = new File(getActiveMQBase() + "/conf");
            System.setProperty("activemq.conf", activeMQConfig.getAbsolutePath());
        }
        return activeMQConfig;
    }

    public File getActiveMQDataDir() {
        File activeMQDataDir = null;

        if (System.getProperty("activemq.data") != null) {
            activeMQDataDir = new File(System.getProperty("activemq.data"));
        } else {
            activeMQDataDir = new File(getActiveMQBase() + "/data");
            System.setProperty("activemq.data", activeMQDataDir.getAbsolutePath());
        }
        return activeMQDataDir;
    }

    public String getExtensionDirForLogging() {
        StringBuilder sb = new StringBuilder("[");
        for (Iterator<File> it = extensions.iterator(); it.hasNext();) {
            File file = it.next();
            sb.append(file.getPath());
            if (it.hasNext()) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

 

  • 大小: 89.6 KB
  • 大小: 62.9 KB
分享到:
评论

相关推荐

    activemq 5.15.1 windows linux 安装jar包 源代码

    本篇文章将详细解析ActiveMQ 5.15.1在Windows和Linux操作系统上的安装过程,以及如何获取和使用源代码。 首先,我们来看ActiveMQ的安装步骤: 1. **下载**: 从Apache官方网站获取ActiveMQ的发行版,这里有两个可供...

    activemq4.0.1源码

    这个源码包"activemq-4.0.1-src.zip"包含了ActiveMQ 4.0.1版本的完整源代码,为开发者提供了深入理解其工作原理的机会。 ActiveMQ的核心特性包括: 1. **高性能与可伸缩性**:ActiveMQ的设计目标之一就是提供高...

    ActiveMQ问题解决记录

    开发者可能遇到的问题可能涉及到配置、性能优化、消息丢失、消息重复、网络中断等问题,这些问题通常需要深入理解ActiveMQ的内部工作原理和源代码来解决。 "工具"标签可能意味着博主使用了一些辅助工具来调试和监控...

    activemq rcp测试例子 不包含依赖库

    5. 调试和优化:根据测试结果,可能需要调试代码或调整ActiveMQ的配置以优化性能和稳定性。 了解这些基本概念后,你可以开始着手搭建环境,运行这个示例,从而深入理解ActiveMQ RCP的工作原理及其在实际应用中的...

    ActiveMQ 使用Ajax 收发消息实战

    标题中的"ActiveMQ 使用Ajax 收发消息实战"指出我们将探讨如何...`src`目录包含源代码,可能包含了与ActiveMQ和Ajax集成的相关Java类和Web资源。然而,具体的实现细节无法从这些文件名中获取,需要查看实际的代码内容。

    activemq-tools-1.5.jar.zip

    `activemq-tools-1.5.jar`就是一个包含了所有相关类和资源的`jar`包,可以直接在Java环境中运行,无需编译源代码。开发者可以通过Java的`java -jar`命令来执行这个工具包,例如: ```bash java -jar activemq-tools...

    ActiveMQ Plugin-开源

    5. **开源特性**:作为开源软件,ActiveMQ Plugin遵循开放源代码协议,允许社区成员自由使用、修改和分发。这意味着用户不仅可以免费使用,还可以根据自身需求定制功能,或者参与项目的改进,推动其不断发展。 6. *...

    spring mq 集成

    标签“源码”意味着文章可能涉及Spring和ActiveMQ的相关源代码分析,帮助读者理解底层工作原理,比如Spring的JMS(Java Message Service)模板是如何与ActiveMQ交互的,或者ActiveMQ的Broker是如何处理消息的。...

    消息中间件ativeMQ相关资料VS2015编译

    2. **获取源码**:从官方网站或者GitHub仓库下载ActiveMQ的源代码。 3. **配置项目**:在VS2015中创建一个新的C++项目,将ActiveMQ-C++的源代码添加到项目中。 4. **设置编译选项**:在项目属性中配置包括路径、链接...

    flex用到JMS代码下载

    此项目可能包括了Flex前端的源代码以及配置文件,展示了如何创建消息生产者(发布消息)和消费者(订阅并接收消息)。 6. **配置与编程**: 在实际操作中,你需要配置BlazeDS以连接到ActiveMQ,设置相应的目的地...

    jms整合spring工程

    - **JmsSpring**:这个目录可能包含了整个工程的源代码,包括配置文件、Java类以及相关的资源文件。 - **配置文件**:如`applicationContext.xml`,可能包含Spring和JMS的相关配置。 - **Java类**:可能有消息...

    jms双系统应用

    而“工具”标签可能指的是博客中提到了一些辅助开发和调试JMS应用的工具,如消息中间件(如Apache ActiveMQ、RabbitMQ或IBM WebSphere MQ)或者是集成开发环境(IDE)的插件等。 在压缩包文件“src”中,通常会包含...

    JMS收发

    至于标签中的“源码”和“工具”,这可能意味着博客可能涉及了JMS的实现原理,例如开源消息中间件如ActiveMQ、RabbitMQ或Kafka的源代码分析,或者是介绍了一些使用JMS的实用工具或库。此外,还可能包含了如何配置和...

    apps.jms.com.co-snv-desarrollo:开发中的 Jms 应用程序

    10. **测试和调试**:在开发过程中,使用模拟的JMS提供者(如ActiveMQ Artemis的In-Memory Broker)进行单元测试,可以帮助快速验证代码的正确性。同时,日志和跟踪工具对于调试JMS应用程序也非常关键。 综上所述,...

Global site tag (gtag.js) - Google Analytics