Jetty
Eclipse Jetty 是轻量级、高度可嵌入的 Java Web 服务器与 Servlet 容器,完整实现 Jakarta EE Servlet / WebSocket 规范。以启动快、内存占用低、模块化著称,常用于嵌入式场景、微服务和 IDE 开发工具(Eclipse、Maven Jetty 插件)。
架构
Server
└── Connector(ServerConnector,监听端口)
└── ConnectionFactory 链(HTTP/1.1 → HTTP/2 → TLS)
└── Handler 树(责任链)
├── HandlerCollection(并行处理)
├── ContextHandlerCollection(按路径分派)
│ └── WebAppContext(一个 war 应用)
└── DefaultHandler(404 等兜底)
Jetty 以Handler 链代替 Tomcat 的 Pipeline/Valve,每个 Handler 决定是否继续向下传递,更灵活。
Spring Boot 集成
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>server:
port: 8080
jetty:
threads:
max: 200
min: 8
idle-timeout: 60000 # 空闲线程存活时间(ms)
max-http-form-post-size: 200000B
connection-idle-timeout: 30000编程式嵌入(不依赖 Spring Boot)
Server server = new Server();
// 配置连接器
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSendServerVersion(false); // 隐藏 Server 版本头
httpConfig.setRequestHeaderSize(8192);
ServerConnector connector = new ServerConnector(server,
new HttpConnectionFactory(httpConfig));
connector.setPort(8080);
connector.setIdleTimeout(30_000);
server.addConnector(connector);
// 配置应用
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("target/myapp.war");
server.setHandler(webapp);
server.start();
server.join();HTTP/2 支持
// 需要 ALPN(TLS 层协商 HTTP 版本)
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfig);
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol("h2");
SslContextFactory.Server sslFactory = new SslContextFactory.Server();
sslFactory.setKeyStorePath("keystore.p12");
sslFactory.setKeyStorePassword("changeit");
SslConnectionFactory ssl = new SslConnectionFactory(sslFactory, alpn.getProtocol());
ServerConnector https = new ServerConnector(server, ssl, alpn, h2,
new HttpConnectionFactory(httpsConfig));
https.setPort(8443);
server.addConnector(https);WebSocket
@WebSocket
public class ChatSocket {
@OnWebSocketMessage
public void onMessage(Session session, String message) throws IOException {
session.getRemote().sendString("Echo: " + message);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("Closed: " + reason);
}
}
// 注册 WebSocket
WebSocketUpgradeFilter.configure(context)
.addMapping("/ws/chat", (req, res) -> new ChatSocket());自定义 Handler(拦截 / 过滤)
// 全局请求日志 Handler
public class AccessLogHandler extends AbstractHandler {
@Override
public void handle(String target, Request baseRequest,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
long start = System.currentTimeMillis();
try {
// 继续传递到下游 Handler
_handler.handle(target, baseRequest, request, response);
} finally {
long elapsed = System.currentTimeMillis() - start;
System.out.printf("[%s] %s %s %dms%n",
request.getMethod(), target,
response.getStatus(), elapsed);
}
}
}JNDI / 资源注入
// 将数据源注入 WebApp JNDI,供 web.xml resource-ref 引用
Resource.setDefaultUseDaemonThreads(true);
EnvEntry maxConn = new EnvEntry(server, "jdbc/max", "20", true);
new Resource("jdbc/dataSource", dataSource);Jetty vs Tomcat
| 特性 | Jetty | Tomcat |
|---|---|---|
| 启动速度 | 极快 | 快 |
| 内存占用 | 低 | 较低 |
| 嵌入式支持 | 极好(设计目标) | 好 |
| 管理界面 | 无 | Manager App |
| HTTP/2 | 支持 | 支持(NIO2) |
| Spring Boot 默认 | 否(需替换依赖) | 是 |
| 社区活跃度 | 中 | 高 |