06月03, 2017

jetty使用

初始化环境

目录初始化

## 可省略直接--add-to-start
java -jar $JETTY_HOME/start.jar --create-startd
java -jar $JETTY_HOME/start.jar --add-to-start=jvm,deploy,server,jsp,jstl,gzip,ext,http,servlets,session-store-mongo,slf4j-log4j2

在jetty.sh中设置

JETTY_BASE=$(cd $(dirname $0);pwd)
NAME=$(basename $JETTY_BASE)
JETTY_PID=${JETTY_BASE}/${NAME}.pid
JETTY_STATE=${JETTY_BASE}/${NAME}.state

更新日志配置

mkdir $JETTY_BASE/resources -p
touch $JETTY_BASE/resources/log4j2.xml
cat > ./resources/log4j2.xml <<END
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="Jetty" >
  <Loggers>
    <Root level="error">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
  <Appenders>
    <Console name="console" target="SYSTEM_ERR">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n</Pattern>
      </PatternLayout>
    </Console>
    <RollingFile name="file"
      fileName="logs/jetty.log"
      filePattern="logs/jetty-%d{MM-dd-yyyy}.log.gz"
      ignoreExceptions="false">
      <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n</Pattern>
      </PatternLayout>
      <SizeBasedTriggeringPolicy size="500MB"/>
      <DefaultRolloverStrategy max="160"/>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="console"/>
      <AppenderRef ref="file"/>
    </Root>
  </Loggers>
</Configuration>
END

jvm参数配置start.d/jvm.ini

-Xms1g
-Xmx2g
-XX:NewSize=256m
-XX:MaxNewSize=512m
-XX:MetaspaceSize=128m
-XX:MaxMetaspaceSize=512m
-XX:-UseBiasedLocking
-XX:-UseCounterDecay
-XX:+AlwaysPreTouch
-XX:AutoBoxCacheMax=20000
-XX:+UseConcMarkSweepGC 
-XX:CMSInitiatingOccupancyFraction=75
-XX:+UseCMSInitiatingOccupancyOnly
-XX:MaxTenuringThreshold=6
-XX:+ExplicitGCInvokesConcurrent
-XX:+ParallelRefProcEnabled
-XX:ErrorFile=/www/logs/hs_err_%p.log
-Xloggc:/www/logs/gc-application_%p.log
-XX:+HeapDumpOnOutOfMemoryError
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-XX:+PrintHeapAtGC
-XX:+PrintTenuringDistribution
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintPromotionFailure
-XX:+UseGCLogFileRotation
-XX:NumberOfGCLogFiles=30
-XX:GCLogFileSize=500M
-Dcom.sun.management.jmxremote
-Djava.rmi.server.hostname=ip
-Dcom.sun.management.jmxremote.port=50001
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dspring.profiles.active=test

参数解析

#2-4G
-Xms1g
-Xmx2g
#-Xmn (等于-XX:NewSize and -XX:MaxNewSize同值的缩写)
#想设置新生代比老生代大就只能用-Xmn
##-Xss在堆之外,线程占用栈内存,默认每条线程为1M(以前是256K),有JSON解析之类的递归调用时不能设太小
#NewRatio默认新生代占堆大小的1/3
#-XX:NewRatio=1
-XX:NewSize=256m
-XX:MaxNewSize=512m
#JDK8的永生代几乎可用完机器的所有内存
-XX:MetaspaceSize=128m
-XX:MaxMetaspaceSize=512m
#-XX:InitialBootClassLoaderMetaspaceSize=256m
#新生代中每个存活区的大小,默认为8,即1/10的新生代 1/(SurvivorRatio+2)
#-XX:SurvivorRatio=8
##堆外内存/直接内存的大小,默认为Heap区总内存减去一个Survivor区的大小
#-XX:MaxDirectMemorySize
#取消偏向锁
-XX:-UseBiasedLocking
-XX:-UseCounterDecay
#-XX:+PerfDisableSharedMem
-XX:+AlwaysPreTouch
-XX:AutoBoxCacheMax=20000
#GC FOR CMS(8G以下的堆)
#-XX:+UseParNewGC
-XX:+UseConcMarkSweepGC 
-XX:CMSInitiatingOccupancyFraction=75
-XX:+UseCMSInitiatingOccupancyOnly
-XX:MaxTenuringThreshold=6
-XX:+ExplicitGCInvokesConcurrent
-XX:+ParallelRefProcEnabled
#多少次Young GC后晋升到年老代
-XX:MaxTenuringThreshold=2
-XX:ErrorFile=/www/logs/hs_err_%p.log
## GC LOG
-Xloggc:/www/logs/gc-www.log
#在Out Of Memory,JVM快死快死掉的时候,输出Heap Dump到指定文件
-XX:+HeapDumpOnOutOfMemoryError
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-XX:+PrintHeapAtGC
-XX:+PrintTenuringDistribution
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintPromotionFailure
-XX:+UseGCLogFileRotation
-XX:NumberOfGCLogFiles=30
-XX:GCLogFileSize=500M
-Dcom.sun.management.jmxremote
-Djava.rmi.server.hostname=ip
-Dcom.sun.management.jmxremote.port=50001
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Dspring.profiles.active=test

mave中使用jetty9.4.6

pom注意

<!-- jetty -->
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-webapp</artifactId>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-servlet</artifactId>
 <version>${jetty.version}</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-annotations</artifactId>
  <version>${jetty.version}</version>
 <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>apache-jsp</artifactId>
  <version>${jetty.version}</version>
 <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>apache-jstl</artifactId>
  <version>${jetty.version}</version>
 <scope>provided</scope>
</dependency>

启动注意

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;


public class JettyStart {
    public static void main(String[] args) {
        new JettyStart().run("/", 8082, ENV_DEV);
    }

    private static final String    DEFAULT_WEBAPP_PATH    = "src/main/webapp";
    private static final String    ACTIVE_PROFILE        = "spring.profiles.active";
    static final String            ENV_DEV                = "dev";
    static final String            ENV_TEST            = "test";
    private Server                server                = null;
    private String                ctx                    = "/";
    private int                    port                = 8082;
    private String                profile                = ENV_DEV;

    private void run(String ctx, int port, String profile) {
        this.ctx = ctx;
        this.port = port;
        if (null != profile) {
            this.profile = profile;
        }
        try {
            start0();
            while (true) {
                int c = System.in.read();
                if (107 == c) {// k
                    stop0();
                    System.exit(-1);
                    break;
                }
                if (c == '\n') {
                    stop0();
                    start0();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void info() {
        System.out.println("运行环境 :" + profile);
        System.out.println("服务地址 :http://localhost:" + port + ctx);
        System.out.println("按回车键重新启动服务.");
        System.out.println("按k+回车键停止服务.");
    }

    private void stop0() throws Exception {

        server.stop();
        server.destroy();
        server = null;
        System.out.println("Stop Ok!");
    }

    private void start0() throws Exception {
        System.setProperty(ACTIVE_PROFILE, profile);
        server = new Server(port);
        WebAppContext webapp = new WebAppContext();
        webapp.setDescriptor(DEFAULT_WEBAPP_PATH + "/WEB-INF/web.xml");
        webapp.setContextPath(ctx);
        webapp.setWar(DEFAULT_WEBAPP_PATH);
        Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
        classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
                "org.eclipse.jetty.annotations.AnnotationConfiguration");
        webapp.setAttribute("org.apache.tomcat.InstanceManager", new org.apache.tomcat.SimpleInstanceManager());
        webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
                ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/shiro-.*\\.jar$|.*/sitemesh.*\\.jar$|.*/spring-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
        server.setHandler(webapp);
        server.setStopAtShutdown(true);
        server.start();
        // server.join();// 如果server没有起来,这里使线程阻塞,保证你的server真正的起来,但是使用了就无法便捷重启!!!
        info();
    }
}

本文链接:https://blog.jnliok.com/post/jetty-use0.html

-- EOF --

Comments