jdk原生的HttpServer(com.sun.net.HttpServer)创建web服务器

编程

最早的学习web编程是写一个Servlet,然后重写里面的service方法,然后去配置web.xml配置,最后部署在tomcat或者jetty等容器中启动。后面是使用一写strtus或者springmvc框架。其实通过jdk源码,可以快速创建web服务,和golang及其的相似。

HttpServer

public static void main(String[] args) {

HttpServer server = HttpServer.create();

server.bind(new InetSocketAddress(8081), 3);

server.createContext("/health", new HealthHandler());

server.createContext("/info", new InfoHandler());

executorService = Executors.newFixedThreadPool(5, DaemonThreadFactory.defaultThreadFactory(daemon));

server.setExecutor(executorService);

server.start();

}

static class HealthHandler implements HttpHandler {

@Override

public void handle(HttpExchange httpExchange) throws IOException {

String responseString = "{"status":"UP"}";

httpExchange.sendResponseHeaders(200, responseString.length());

OutputStream os = httpExchange.getResponseBody();

os.write(responseString.getBytes());

os.close();

}

}

static class InfoHandler implements HttpHandler {

@Override

public void handle(HttpExchange httpExchange) throws IOException {

String responseString = "{}";

httpExchange.sendResponseHeaders(200, responseString.length());

OutputStream os = httpExchange.getResponseBody();

os.write(responseString.getBytes());

os.close();

}

}

以上是 jdk原生的HttpServer(com.sun.net.HttpServer)创建web服务器 的全部内容, 来源链接: utcz.com/z/518526.html

回到顶部