使用Java写一个简易web服务器来替代nginx功能。
main:
public static void main(String[] args) {
ServerConfigLoader serverConfigLoader = Factory.serverConfigLoader();
ServerConfig serverConfig = serverConfigLoader.getServerConfig();
HttpServer httpServer = SimpleFileServer.createFileServer(new InetSocketAddress(Integer.parseInt(serverConfig.serverPort())),
Path.of(serverConfig.contextLocation()), SimpleFileServer.OutputLevel.VERBOSE);
httpServer.start();
}
config:
public class ServerConfigLoader {
private ServerConfig serverConfig;
public ServerConfigLoader() {
String configFileName = "server.properties";
try (InputStream input = ServerConfigLoader.class.getClassLoader().getResourceAsStream(configFileName)) {
Properties prop = new Properties();
prop.load(input);
this.serverConfig = new ServerConfig(prop.getProperty("server.port"), prop.getProperty("context.location"));
} catch (IOException ex) {
System.out.println("Start web server failed: " + ex.getLocalizedMessage());
ex.printStackTrace();
}
}
public ServerConfig getServerConfig() {
return serverConfig;
}
}
public record ServerConfig(String serverPort, String contextLocation) {
}
public class Factory {
public static ServerConfigLoader serverConfigLoader() {
return new ServerConfigLoader();
}
}
到此,极简web server就写完了。
配置文件:
server.properties
server.port=8080
context.location=D:\your-dictionary
© 版权声明
特别提醒: 内容为用户自行发布,如有侵权,请联系我们管理员删除,邮箱:mail@xieniao.com ,在收到您的邮件后我们会在3个工作日内处理。
相关文章
暂无评论...