07 October 2014

In a previous post, I discussed how to use Jetty as the servlet container in a Spring Boot application over the default implementation (Apache Tomcat) and also how to enable Jetty's registered MBeans via JMX. In addition to this configuration, you can also configure Jetty so that it is not using the factory default settings for the servlet container. One setting that you typically want to control is the size of the thread pool used by Jetty to service incoming requests. This is pretty easy to do with Spring Boot by adding a JettyServerCustomizer implementation to gain access to Jetty's Server instance:

@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(@Value("${server.port:8080}") final String port,
            @Value("${jetty.threadPool.maxThreads:200}") final String maxThreads,
            @Value("${jetty.threadPool.minThreads:8}") final String minThreads,
            @Value("${jetty.threadPool.idleTimeout:60000}") final String idleTimeout) {
    final JettyEmbeddedServletContainerFactory factory =  new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
    factory.addServerCustomizers(new JettyServerCustomizer() {
        @Override
        public void customize(final Server server) {
            // Tweak the connection pool used by Jetty to handle incoming HTTP connections
            final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
            threadPool.setMaxThreads(Integer.valueOf(maxThreads));
            threadPool.setMinThreads(Integer.valueOf(minThreads));
            threadPool.setIdleTimeout(Integer.valueOf(idleTimeout));
        }
    });

    return factory;
}

In the example above, values (with defaults) are read from the Spring configuration and used to set the thread pool managed by Jetty. In order to make this work, you must include the following dependencies with your application:

ext {
    jettyVersion = '9.0.3.v20130506'
}

dependencies {
  ...

  compile "org.eclipse.jetty:jetty-server:$jettyVersion"
  compile "org.eclipse.jetty:jetty-util:$jettyVersion"

  ...
}

This example can be extended to configure any bean registered with the Jetty Server instance. To figure out what is available, connect to your running application using a JMX console and view the beans exposed by Jetty.

comments powered by Disqus