Jetty REST API 动态调整 QueuedThreadPool maxThreads

Jetty REST API to Dynamically adjust QueuedThreadPool maxThreads

从 jetty 配置中设置 min/max 个线程很容易:

<Configure id="server" class="org.eclipse.jetty.server.Server">   
<Set name="threadPool">
    <New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
      <Set name="minThreads">10</Set>
      <Set name="maxThreads">1000</Set>
    </New>
</Set> 
</Configure>

我正在使用 Spring 并且我有一个 REST 端点:

@RequestMapping("/setMaxThreads")
public void setMaxThreads(...) {
    ...
}

如何访问 Server/ThreadPool 对象以调整它们的参数?

P.S。我知道任何解决方案都可能不会非常通用,因为这些是非常特定于实现的参数。

你甚至不能再做你在 jetty.xml 例子中描述的事情了。

Jetty ServerThreadPool 现在只设置 via its constructor。 运行时无法调整。

This change from .setThreadPool(ThreadPool) to Server constructor based occurred at the start of Jetty 9.x, and was to address the threadpool needs of both Servlet 3.1 and HTTP/2 support.

原因是 ThreadPool 在这些层的初始化期间被注入到其他几十个层中,甚至在 Server[= 的 LifeCycle 启动期间注入更多28=]

如果您的目标是对线程池大小的上限进行某种过早优化?

现在停止。

自 Servlet 3.0 起,绑定(上限)线程池对于可公开访问的 Jetty 服务器完全没有意义。

您向微不足道的 DoS 攻击、失败的选择器处理、死连接、看似随机的 EOF 异常等开放自己...

不要优化线程池上端,然后期望 Jetty 处理高负载场景。

在高负载情况下,QueuedThreadPool(暂时)达到 20,000 甚至 50,000 个活动线程的情况并不少见。当服务器负载下降时,QueuedThreadPool 管理的线程数也会下降。如果需要,QueuedThreadPool 将快速增加线程数,但从池中删除线程是有意计量的。

如果您是一个 运行 Jetty,在一个非常受控的小负载场景中,那么可以随意用您自己的声明完全替换 QueuedThreadPool。我们建议您使用 ExecutorThreadPool,它具有您自己选择的 java.util.concurrent.ExecutorService 实现。

ExecutorThreadPool 示例:

    int corePoolSize = 400;
    int maximumPoolSize = 1_000_000;
    long keepaliveTimeout = 60L;
    TimeUnit keepaliveUnit = TimeUnit.SECONDS;
    BlockingQueue<Runnable> workQueue = new SynchronousQueue<Runnable>();

    ExecutorService cachedExecutor = new ThreadPoolExecutor(
            corePoolSize, 
            maximumPoolSize,
            keepaliveTimeout,
            keepaliveUnit,
            workQueue);

    ExecutorThreadPool threadpool = new ExecutorThreadPool(cachedExecutor);
    Server server = new Server(threadpool);