jetty 9 嵌入式开发示例

时间:2021-07-31 22:35:19

jetty 9 嵌入应用程序后,小型的web应用直接打成一个单独的jar包,就可以直接运行,非常适合做Demo演示或云端集群部署。

主要代码:

JettyServer的封装类

 package yjmyzz.jetty.demo.server;

 import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.LoggerFactory; import java.io.File; public class JettyWebServer { private static org.slf4j.Logger logger = LoggerFactory.getLogger(JettyWebServer.class); private Server server;
private int port;
private String host;
private String tempDir;
private String logDir;
private String webDir;
private String contextPath; public JettyWebServer(int port, String host, String tempDir, String webDir, String logDir, String contextPath) { logger.info("port:{},host:{},tempDir:{},webDir:{},logDir:{},contextPath:{}", port, host, tempDir, webDir, logDir, contextPath); this.port = port;
this.host = host;
this.tempDir = tempDir;
this.webDir = webDir;
this.contextPath = contextPath;
this.logDir = logDir;
} public void start() throws Exception {
server = new Server(createThreadPool());
server.addConnector(createConnector());
server.setHandler(createHandlers());
server.setStopAtShutdown(true);
server.start();
} public void join() throws InterruptedException {
server.join();
} private ThreadPool createThreadPool() {
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(10);
threadPool.setMaxThreads(100);
return threadPool;
} private NetworkConnector createConnector() {
ServerConnector connector = new ServerConnector(server);
connector.setPort(port);
connector.setHost(host);
return connector;
} private HandlerCollection createHandlers() {
WebAppContext context = new WebAppContext();
context.setContextPath(contextPath);
context.setWar(webDir);
context.setTempDirectory(new File(tempDir)); RequestLogHandler logHandler = new RequestLogHandler();
logHandler.setRequestLog(createRequestLog());
GzipHandler gzipHandler = new GzipHandler();
HandlerCollection handlerCollection = new HandlerCollection();
handlerCollection.setHandlers(new Handler[]{context, logHandler, gzipHandler});
return handlerCollection;
} private RequestLog createRequestLog() {
//记录访问日志的处理
NCSARequestLog requestLog = new NCSARequestLog();
requestLog.setFilename(logDir + "/yyyy-mm-dd.log");
requestLog.setRetainDays(90);
requestLog.setExtended(false);
requestLog.setAppend(true);
//requestLog.setLogTimeZone("GMT");
requestLog.setLogTimeZone("Asia/Shanghai");
requestLog.setLogDateFormat("yyyy-MM-dd HH:mm:ss SSS");
requestLog.setLogLatency(true);
return requestLog;
} }

启动代码示例:

 package yjmyzz.jetty.demo.main;

 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import yjmyzz.jetty.demo.server.JettyWebServer;
import yjmyzz.jetty.demo.util.FileUtil;
import yjmyzz.jetty.demo.util.JarUtils; import java.util.HashMap;
import java.util.Map; public class JettyApp { private static final String PORT = "port";
private static final String WEB_DIR = "web";
private static final String LOG_DIR = "log";
private static final String TEMP_DIR = "temp";
private static final String CONTEXT_PATH = "context";
private static final String HOST = "host";
private static final Map<String, String> param = new HashMap<>();
private static Logger logger = LoggerFactory.getLogger(JettyWebServer.class); public static void main(String... anArgs) throws Exception { if (anArgs.length == 0) {
param.put(PORT, "8080");
param.put(WEB_DIR, "web");
param.put(LOG_DIR, "logs");
param.put(TEMP_DIR, "temp");
param.put(CONTEXT_PATH, "/demo");
param.put(HOST, "localhost");
} for (String arg : anArgs) {
System.out.println(arg);
if (!StringUtils.isEmpty(arg) && arg.contains("=")) {
String[] t = arg.trim().split("=");
param.put(t[0], t[1]);
}
} initParam(); unzipSelf(); new JettyApp().start();
} private static void initParam() { String logDir = FileUtil.currentWorkDir + param.get(LOG_DIR);
String tempDir = FileUtil.currentWorkDir + param.get(TEMP_DIR);
String webDir = FileUtil.currentWorkDir + param.get(WEB_DIR); logger.debug(logDir);
logger.debug(tempDir);
logger.debug(webDir); String temp = "x.x";//占位
FileUtil.createDirs(logDir + "/" + temp);
FileUtil.createDirs(tempDir + "/" + temp);
FileUtil.createDirs(webDir + "/" + temp); param.put(LOG_DIR, logDir);
param.put(TEMP_DIR, tempDir);
param.put(WEB_DIR, webDir);
} private JettyWebServer server; public JettyApp() {
server = new JettyWebServer(
Integer.parseInt(param.get(PORT).toString()),
param.get(HOST),
param.get(TEMP_DIR),
param.get(WEB_DIR),
param.get(LOG_DIR),
param.get(CONTEXT_PATH));
} public void start() throws Exception {
server.start();
server.join();
} private static void unzipSelf() {
//将jar自身解压 String selfPath = FileUtil.getJarExecPath(JettyApp.class);
if (selfPath.endsWith(".jar")) {
// 运行环境
try {
logger.info("正在将\n" + selfPath + "\n解压至\n" + param.get(WEB_DIR));
JarUtils.unJar(selfPath, param.get(WEB_DIR));
} catch (Exception e) {
logger.error("解压web内容失败!", e);
}
} else {
// IDE环境
param.put(WEB_DIR, selfPath);
}
logger.info(selfPath);
}
}

我在github上开源了一个jetty9 + spring mvc4 + velocity2的示例项目,地址:https://github.com/yjmyzz/jetty-embed-demo