【问题标题】:Can I make a Java HttpServer threaded/process requests in parallel?我可以并行创建 Java HttpServer 线程/处理请求吗?
【发布时间】:2019-02-25 21:55:37
【问题描述】:

根据我在网上找到的教程,我使用 Sun 的轻量级 HttpServer 构建了一个简单的 HttpServer。

main函数基本上是这样的:

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://localhost:8000/[context]?int="+threadID

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

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

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

或者我应该完全放弃使用 Sun 的轻量级服务器并专注于从头开始构建一些东西?

感谢您的帮助。

【问题讨论】:

标签: java httpserver


【解决方案1】:

正如您在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 限制线程数。

【讨论】:

  • 感谢您的快速回复。我会更多地研究执行者,看看我是否能更好地理解:)
  • 快速提问:executor 现在是在某种意义上替换了处理程序还是有所不同?
  • 不,只有“服务”任务的方式。使用 newCahdedThreadPool(),它将根据请求创建尽可能多的线程。但是你的处理程序会像往常一样被调用。注意,如果你重用同一个处理程序,他必须是 ThreadSafe。
  • 看起来它与 newFixedThreadPool 一起工作得很好,但我需要更多地研究 executors。非常感谢您的回答!
  • @Hoysala 服务器是同步的:他监听端口,接受套接字并启动一个新线程
【解决方案2】:

您使用了 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();
}

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 2023-03-27
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2021-07-11
    相关资源
    最近更新 更多