Jetty服务器

Jetty 是一个开源的servlet容器,它为基于Java的web内容,例如JSP和servlet提供运行环境。Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布。

使用 Jetty 启动服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public class ApiServer {
public static void main(String[] args) {
final ApiServer apiServer = new ApiServer();
try {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
java.security.Security.setProperty("networkaddress.cache.ttl" , "10");

ServiceConfig config = ServiceConfig.getInstance();
boolean result = config.init(confFile);
if (!result) {
LOGGER.error("failed to init ServerConfig, exiting...");
System.exit(EXIT_CODE);
}

boolean initServiceSuccess = apiServer.initService(serverConfig);
if (!initServiceSuccess) {
System.exit(EXIT_CODE);
}

Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
apiServer.stopServer();
}
});

apiServer.startServer(config);

} catch (Exception e) {
LOGGER.error("message api error,", e);
}
}

private boolean initService(MessageConfig serverConfig) {
// TODO, init depend service, MySQL, Kafka, Redis, Zookeeper
return ture;
}

private void startServer(ServiceConfig serverConfig) throws Exception {
ResourceConfig config = new ResourceConfig();
config.packages(ApiServer.class.getPackage().getName());
config.register(BasicFilter.class);
config.register(LoggingFilter.class);
config.register(CharsetResponseFilter.class);
ServletHolder servlet = new ServletHolder(new ServletContainer(config));

server = new Server(HTTP_PORT);
ServletContextHandler context = new ServletContextHandler(server, "/*");
context.addServlet(servlet, "/*");

//gracefully shutdown jetty config
server.setStopAtShutdown(true);
server.setStopTimeout(3000L);//3 second

try {
server.start();
LOGGER.info("api server started, port {}", HTTP_PORT);
server.join();
} finally {
if (!server.isStopped()) {
server.destroy();
}
}
}

private void stopServer() {
try {
LOGGER.info("close api server...");
server.stop();
} catch (Exception e) {
LOGGER.error("close api server error", e);
}
// TODO, stop service which depend
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ResourceConfig config = new ResourceConfig();
config.packages(ApiServer.class.getPackage().getName());
config.register(BasicFilter.class);
config.register(LoggingFilter.class);
config.register(CharsetResponseFilter.class);
ServletHolder servlet = new ServletHolder(new ServletContainer(config));

server = new Server(HTTP_PORT);
ServletContextHandler context = new ServletContextHandler(server, "/*");
context.addServlet(servlet, "/*");

server.setStopAtShutdown(true);
server.setStopTimeout(3000L);//3 second
server.start();
server.join();

通过 register 函数注册 Filter 类,在 Filter 类中会重写 filter 函数处理请求或响应。