我可以并行创建Java HttpServer线程/进程请求吗?

问题描述 投票:9回答:2

我已经使用Sun的轻量级HttpServer在线发现了一个简单的HttpServer。

基本上主要功能如下:

public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        //Create the context for the server.
        server.createContext("/", new BaseHandler());

        server.setExecutor(null); // creates a default executor
        server.start();
    }

我已经实现了BaseHandler接口的方法来处理Http请求并返回响应。

static class BaseHandler implements HttpHandler {
        //Handler method
        public void handle(HttpExchange t) throws IOException {

          //Implementation of http request processing
          //Read the request, get the parameters and print them
          //in the console, then build a response and send it back.
        }
  }

我还创建了一个通过线程发送多个请求的客户端。每个线程将以下请求发送到服务器:

HTTP://本地主机:8000 / [上下文] INT =“+线程ID

在每个客户端运行时,请求似乎以不同的顺序到达服务器,但它们以串行方式提供。

我希望实现的是,如果可能的话,以并行方式处理请求。

例如,是否可以在单独的线程中运行每个处理程序,如果是这样,那么它是否是一件好事。

或者我应该完全放弃使用Sun的轻量级服务器并从头开始关注建筑物?

谢谢你的帮助。

java httpserver
2个回答
19
投票

正如您在ServerImpl中看到的,默认执行程序只是“运行”任务:

  157       private static class DefaultExecutor implements Executor {
  158           public void execute (Runnable task) {
  159               task.run();
  160           }
  161       }

您必须为您的httpServer提供一个真正的执行程序,如下所示:

server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());

并且您的服务器将并行运行。小心,这是一个非限制性的Executor,请参阅Executors.newFixedThreadPool来限制Thread的数量。


0
投票

您使用了在同一调用方线程中运行处理程序的server.setExecutor(null)。在这种情况下,运行服务器的主线程。

您只需将行更改为

public static void main(String[] args) throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
    //Create the context for the server.
    server.createContext("/", new BaseHandler());
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
}
© www.soinside.com 2019 - 2024. All rights reserved.