使用Jetty启动服务
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
}
}
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函数处理请求或响应。
网友评论