1. 程式人生 > >一.配置簡單的嵌入式tomcat和jetty

一.配置簡單的嵌入式tomcat和jetty

pos catalina after details pat number app ber href

我們寫了一個web應用,打成war包後,就需要找一個server來部署.對於我們的實際應用,我們基本沒必要自己再寫一個嵌入式的server.接下來兩篇文章只是以鉆研的心態來學習一下嵌入式tomcat和jetty. 促使我去寫這篇文章是因為在我看來,gretty不完美,無論用tomcat還是jetty,修改類之後,reload幾次內存占用高漲,硬盤讀寫頻繁,最終感到無奈(應用存在內存不正確釋放,或許我使用的方式不對).
我選用了<<gradle的war插件>>簡單開發的web應用,此例主要開發框架:springmvc(java config方式)+spring data jpa(jpa由hibernate實現)+mysql,開發IDE工具:idea13.1,項目管理工具:gradle,源碼下載:http://download.csdn.net/detail/xiejx618/7696821 一.war包配置的嵌入式tomcat例子. 1.運行一下war任務,對這個web應用打成war包.然後再解壓一下這個包.

2.再新建一個gradle項目

a.build.gradle

[plain] view plain copy print?
  1. apply plugin: ‘java‘
  2. sourceCompatibility = 1.6
  3. version = ‘1.0‘
  4. repositories {
  5. mavenCentral()
  6. }
  7. dependencies {
  8. compile("org.apache.tomcat.embed:tomcat-embed-jasper:8.0.9")
  9. compile("org.apache.tomcat.embed:tomcat-embed-core:8.0.9")
  10. compile("org.apache.tomcat.embed:tomcat-embed-logging-juli:8.0.9")
  11. compile("org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.0.9")
  12. compile("org.apache.tomcat.embed:tomcat-embed-el:8.0.9")
  13. compile("org.apache.tomcat.embed:tomcat-embed-websocket:8.0.9")
  14. compile("org.eclipse.jdt.core.compiler:ecj:4.4")
  15. }
apply plugin: ‘java‘
sourceCompatibility = 1.6
version = ‘1.0‘
repositories {
    mavenCentral()
}
dependencies {
    compile("org.apache.tomcat.embed:tomcat-embed-jasper:8.0.9")
    compile("org.apache.tomcat.embed:tomcat-embed-core:8.0.9")
    compile("org.apache.tomcat.embed:tomcat-embed-logging-juli:8.0.9")
    compile("org.apache.tomcat.embed:tomcat-embed-logging-log4j:8.0.9")
    compile("org.apache.tomcat.embed:tomcat-embed-el:8.0.9")
    compile("org.apache.tomcat.embed:tomcat-embed-websocket:8.0.9")
    compile("org.eclipse.jdt.core.compiler:ecj:4.4")
}

compile("org.eclipse.jdt.core.compiler:ecj:4.4")相當重要,沒有此jar包,類加載器就沒有加載部分類的字節碼,我多次調試才找到問題. 當然,也可以建一個java工程,到http://tomcat.apache.org/download-80.cgi下載Binary Distributions的Embedded包(下載地址:http://mirrors.cnnic.cn/apache/tomcat/tomcat-8/v8.0.9/bin/embed/apache-tomcat-8.0.9-embed.zip),把裏面的所有jar包加到工程的Libraries就可以了. b.新建一個含有main方法的可執行類(此類的編寫參考了Aleksa Vukotic James Goodwill寫的<<Apache Tomcat 7>>CHAPTER9 Embedding Tomcat).

[java] view plain copy print?
  1. import org.apache.catalina.LifecycleException;
  2. import org.apache.catalina.core.AprLifecycleListener;
  3. import org.apache.catalina.core.StandardServer;
  4. import org.apache.catalina.startup.ClassLoaderFactory;
  5. import org.apache.catalina.startup.Tomcat;
  6. import javax.servlet.ServletException;
  7. /**
  8. * Created by nil on 2014/8/1.
  9. */
  10. public class EmbeddedTomcat {
  11. private Tomcat tomcat;
  12. private void startTomcat(int port,String contextPath,String baseDir) throws ServletException, LifecycleException {
  13. tomcat = new Tomcat();
  14. tomcat.setPort(port);
  15. tomcat.setBaseDir(".");
  16. StandardServer server = (StandardServer) tomcat.getServer();
  17. AprLifecycleListener listener = new AprLifecycleListener();
  18. server.addLifecycleListener(listener);
  19. tomcat.addWebapp(contextPath, baseDir);
  20. tomcat.start();
  21. }
  22. private void stopTomcat() throws LifecycleException {
  23. tomcat.stop();
  24. }
  25. public static void main(String[] args) {
  26. try {
  27. int port=8080;
  28. String contextPath = "/test";
  29. String baseDir = "C:/Users/nil/AppData/Local/Temp/jetty-0.0.0.0-8080-test-1.0.war-_test-any-8966644989981380511.dir/webapp";
  30. EmbeddedTomcat tomcat = new EmbeddedTomcat();
  31. tomcat.startTomcat(port, contextPath, baseDir);
  32. //由於Tomcat的start方法為非阻塞方法,加一個線程睡眠模擬線程阻塞.
  33. Thread.sleep(10000000);
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.ClassLoaderFactory;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
/**
 * Created by nil on 2014/8/1.
 */
public class EmbeddedTomcat {
    private Tomcat tomcat;
    private void startTomcat(int port,String contextPath,String baseDir) throws ServletException, LifecycleException {
        tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.setBaseDir(".");
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        server.addLifecycleListener(listener);
        tomcat.addWebapp(contextPath, baseDir);
        tomcat.start();
    }
    private void stopTomcat() throws LifecycleException {
        tomcat.stop();
    }
    public static void main(String[] args) {
        try {
            int port=8080;
            String contextPath = "/test";
            String baseDir = "C:/Users/nil/AppData/Local/Temp/jetty-0.0.0.0-8080-test-1.0.war-_test-any-8966644989981380511.dir/webapp";
            EmbeddedTomcat tomcat = new EmbeddedTomcat();
            tomcat.startTomcat(port, contextPath, baseDir);
            //由於Tomcat的start方法為非阻塞方法,加一個線程睡眠模擬線程阻塞.
            Thread.sleep(10000000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

其中baseDir為前面war解壓的路徑,另兩個參數port和contextPath是容易理解的. c.運行一下main方法,就可以通過瀏覽器來訪問這個web應用了.

二.war包配置的嵌入式jetty例子. 1.運行一下war任務,對這個web應用打成war包. 2.再新建一個gradle項目. a.build.gradle

[plain] view plain copy print?
  1. apply plugin: ‘java‘
  2. sourceCompatibility = 1.6
  3. version = ‘1.0‘
  4. repositories {
  5. mavenCentral()
  6. }
  7. dependencies {
  8. compile("org.eclipse.jetty:example-jetty-embedded:9.2.1.v20140609")
  9. compile("org.eclipse.jetty:jetty-jsp:9.2.1.v20140609")
  10. }
apply plugin: ‘java‘
sourceCompatibility = 1.6
version = ‘1.0‘
repositories {
    mavenCentral()
}
dependencies {
    compile("org.eclipse.jetty:example-jetty-embedded:9.2.1.v20140609")
    compile("org.eclipse.jetty:jetty-jsp:9.2.1.v20140609")
}

b.新建一個含有main方法的可執行類(此類的編寫主要參考jetty官方文檔:http://www.eclipse.org/jetty/documentation/current/using-annotations-embedded.html).

[java] view plain copy print?
  1. import org.eclipse.jetty.server.Server;
  2. import org.eclipse.jetty.webapp.*;
  3. /**
  4. * Created by nil on 2014/8/2.
  5. */
  6. public class Main {
  7. //Create a WebApp
  8. private static WebAppContext getWebAppContext(){
  9. WebAppContext webapp = new WebAppContext();
  10. webapp.setContextPath("/");
  11. webapp.setWar("E:/idea/test/build/libs/test-1.0.war");
  12. return webapp;
  13. }
  14. public static void appStart() throws Exception {
  15. Server server = new Server(8080);
  16. //Enable parsing of jndi-related parts of web.xml and jetty-env.xml
  17. org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
  18. classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
  19. classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
  20. //get a WebAppContext
  21. server.setHandler(getWebAppContext());
  22. server.start();
  23. server.join();
  24. }
  25. public static void main(String[] args) throws Exception {
  26. appStart();
  27. }
  28. }
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.*;
/**
 * Created by nil on 2014/8/2.
 */
public class Main {
    //Create a WebApp
    private static WebAppContext getWebAppContext(){
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setWar("E:/idea/test/build/libs/test-1.0.war");
        return webapp;
    }
    public static void appStart() throws Exception {
        Server server = new Server(8080);
        //Enable parsing of jndi-related parts of web.xml and jetty-env.xml
        org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
        classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
        classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
        //get a WebAppContext
        server.setHandler(getWebAppContext());
        server.start();
        server.join();
    }
    public static void main(String[] args) throws Exception {
        appStart();
    }
}

appStart方法內第3-5行是為了支持servlet3特性.其中上面的setWar這裏就是上面打包的war包路徑. c.運行一下main方法,就可以通過瀏覽器來訪問這個web應用了.

一.配置簡單的嵌入式tomcat和jetty