jetty 9 嵌入式开发示例

时间:2022-04-22
本文章向大家介绍jetty 9 嵌入式开发示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

主要代码:

JettyServer的封装类

 1 package yjmyzz.jetty.demo.server;
 2 
 3 import org.eclipse.jetty.server.*;
 4 import org.eclipse.jetty.server.handler.HandlerCollection;
 5 import org.eclipse.jetty.server.handler.RequestLogHandler;
 6 import org.eclipse.jetty.server.handler.gzip.GzipHandler;
 7 import org.eclipse.jetty.util.thread.QueuedThreadPool;
 8 import org.eclipse.jetty.util.thread.ThreadPool;
 9 import org.eclipse.jetty.webapp.WebAppContext;
10 import org.slf4j.LoggerFactory;
11 
12 import java.io.File;
13 
14 public class JettyWebServer {
15 
16     private static org.slf4j.Logger logger = LoggerFactory.getLogger(JettyWebServer.class);
17 
18     private Server server;
19     private int port;
20     private String host;
21     private String tempDir;
22     private String logDir;
23     private String webDir;
24     private String contextPath;
25 
26 
27     public JettyWebServer(int port, String host, String tempDir, String webDir, String logDir, String contextPath) {
28 
29         logger.info("port:{},host:{},tempDir:{},webDir:{},logDir:{},contextPath:{}", port, host, tempDir, webDir, logDir, contextPath);
30 
31         this.port = port;
32         this.host = host;
33         this.tempDir = tempDir;
34         this.webDir = webDir;
35         this.contextPath = contextPath;
36         this.logDir = logDir;
37     }
38 
39     public void start() throws Exception {
40         server = new Server(createThreadPool());
41         server.addConnector(createConnector());
42         server.setHandler(createHandlers());
43         server.setStopAtShutdown(true);
44         server.start();
45     }
46 
47     public void join() throws InterruptedException {
48         server.join();
49     }
50 
51 
52     private ThreadPool createThreadPool() {
53         QueuedThreadPool threadPool = new QueuedThreadPool();
54         threadPool.setMinThreads(10);
55         threadPool.setMaxThreads(100);
56         return threadPool;
57     }
58 
59 
60     private NetworkConnector createConnector() {
61         ServerConnector connector = new ServerConnector(server);
62         connector.setPort(port);
63         connector.setHost(host);
64         return connector;
65     }
66 
67     private HandlerCollection createHandlers() {
68         WebAppContext context = new WebAppContext();
69         context.setContextPath(contextPath);
70         context.setWar(webDir);
71         context.setTempDirectory(new File(tempDir));
72 
73 
74         RequestLogHandler logHandler = new RequestLogHandler();
75         logHandler.setRequestLog(createRequestLog());
76         GzipHandler gzipHandler = new GzipHandler();
77         HandlerCollection handlerCollection = new HandlerCollection();
78         handlerCollection.setHandlers(new Handler[]{context, logHandler, gzipHandler});
79         return handlerCollection;
80     }
81 
82     private RequestLog createRequestLog() {
83         //记录访问日志的处理
84         NCSARequestLog requestLog = new NCSARequestLog();
85         requestLog.setFilename(logDir + "/yyyy-mm-dd.log");
86         requestLog.setRetainDays(90);
87         requestLog.setExtended(false);
88         requestLog.setAppend(true);
89         //requestLog.setLogTimeZone("GMT");
90         requestLog.setLogTimeZone("Asia/Shanghai");
91         requestLog.setLogDateFormat("yyyy-MM-dd HH:mm:ss SSS");
92         requestLog.setLogLatency(true);
93         return requestLog;
94     }
95 
96 }

启动代码示例:

  1 package yjmyzz.jetty.demo.main;
  2 
  3 import org.slf4j.Logger;
  4 import org.slf4j.LoggerFactory;
  5 import org.springframework.util.StringUtils;
  6 import yjmyzz.jetty.demo.server.JettyWebServer;
  7 import yjmyzz.jetty.demo.util.FileUtil;
  8 import yjmyzz.jetty.demo.util.JarUtils;
  9 
 10 import java.util.HashMap;
 11 import java.util.Map;
 12 
 13 public class JettyApp {
 14 
 15     private static final String PORT = "port";
 16     private static final String WEB_DIR = "web";
 17     private static final String LOG_DIR = "log";
 18     private static final String TEMP_DIR = "temp";
 19     private static final String CONTEXT_PATH = "context";
 20     private static final String HOST = "host";
 21     private static final Map<String, String> param = new HashMap<>();
 22     private static Logger logger = LoggerFactory.getLogger(JettyWebServer.class);
 23 
 24 
 25     public static void main(String... anArgs) throws Exception {
 26 
 27         if (anArgs.length == 0) {
 28             param.put(PORT, "8080");
 29             param.put(WEB_DIR, "web");
 30             param.put(LOG_DIR, "logs");
 31             param.put(TEMP_DIR, "temp");
 32             param.put(CONTEXT_PATH, "/demo");
 33             param.put(HOST, "localhost");
 34         }
 35 
 36 
 37         for (String arg : anArgs) {
 38             System.out.println(arg);
 39             if (!StringUtils.isEmpty(arg) && arg.contains("=")) {
 40                 String[] t = arg.trim().split("=");
 41                 param.put(t[0], t[1]);
 42             }
 43         }
 44 
 45         initParam();
 46 
 47         unzipSelf();
 48 
 49         new JettyApp().start();
 50     }
 51 
 52 
 53     private static void initParam() {
 54 
 55 
 56         String logDir = FileUtil.currentWorkDir + param.get(LOG_DIR);
 57         String tempDir = FileUtil.currentWorkDir + param.get(TEMP_DIR);
 58         String webDir = FileUtil.currentWorkDir + param.get(WEB_DIR);
 59 
 60         logger.debug(logDir);
 61         logger.debug(tempDir);
 62         logger.debug(webDir);
 63 
 64         String temp = "x.x";//占位
 65         FileUtil.createDirs(logDir + "/" + temp);
 66         FileUtil.createDirs(tempDir + "/" + temp);
 67         FileUtil.createDirs(webDir + "/" + temp);
 68 
 69         param.put(LOG_DIR, logDir);
 70         param.put(TEMP_DIR, tempDir);
 71         param.put(WEB_DIR, webDir);
 72     }
 73 
 74     private JettyWebServer server;
 75 
 76     public JettyApp() {
 77         server = new JettyWebServer(
 78                 Integer.parseInt(param.get(PORT).toString()),
 79                 param.get(HOST),
 80                 param.get(TEMP_DIR),
 81                 param.get(WEB_DIR),
 82                 param.get(LOG_DIR),
 83                 param.get(CONTEXT_PATH));
 84     }
 85 
 86     public void start() throws Exception {
 87         server.start();
 88         server.join();
 89     }
 90 
 91     private static void unzipSelf() {
 92         //将jar自身解压
 93 
 94         String selfPath = FileUtil.getJarExecPath(JettyApp.class);
 95         if (selfPath.endsWith(".jar")) {
 96             // 运行环境
 97             try {
 98                 logger.info("正在将n" + selfPath + "n解压至n" + param.get(WEB_DIR));
 99                 JarUtils.unJar(selfPath, param.get(WEB_DIR));
100             } catch (Exception e) {
101                 logger.error("解压web内容失败!", e);
102             }
103         } else {
104             // IDE环境
105             param.put(WEB_DIR, selfPath);
106         }
107         logger.info(selfPath);
108     }
109 }

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