Beginner spring boot (custom tomcat container)--002

 

One: spring boot custom tomcat container

 

1. First, spring boot initializes various autowiring and beans by annotating @EnableAutoConfiguration, which registers TomcatEmbeddedServletContainerFactory to DefaultListableBeanFactory by default.

 

2. Convert to java language: customize a bean. The first reaction is to learn from the spring aop idea and inherit the BeanPostProcessor custom bean.

 

3. The default implementation of spring boot is to customize the tomcat container through EmbeddedServletContainerCustomizerBeanPostProcessor, which can be extended through the EmbeddedServletContainerCustomizer interface

 

4. The second way is to customize a bean: EmbeddedServletContainerFactory.

 

Implement Demo:

@Component
public class TomcatContainerCustomizer implements EmbeddedServletContainerCustomizer {

  private static final Logger logger = LoggerFactory.getLogger(TomcatContainerCustomizer.class);
  private static final String TOMCAT_ACCEPTOR_COUNT = "server.tomcat.accept-count";
  @Autowired
  private Environment environment;

  @Override
  public void customize(ConfigurableEmbeddedServletContainer container) {
    if (!(container instanceof TomcatEmbeddedServletContainerFactory)) {
      return;
    }
    if (!environment.containsProperty(TOMCAT_ACCEPTOR_COUNT)) {
      return;
    }
    TomcatEmbeddedServletContainerFactory tomcat =
        (TomcatEmbeddedServletContainerFactory) container;
    tomcat.addConnectorCustomizers(new TomcatConnectorCustomizer() {
      @Override
      public void customize(Connector connector) {
        ProtocolHandler handler = connector.getProtocolHandler();
        if (handler instanceof Http11NioProtocol) {
          Http11NioProtocol http = (Http11NioProtocol) handler;
          int acceptCount = Integer.parseInt(environment.getProperty(TOMCAT_ACCEPTOR_COUNT));
          http.setBacklog(acceptCount);
          logger.info("Setting tomcat accept count to {}", acceptCount);
        }

      }
    });
  }
}

 

Related source code screenshots:

EmbeddedWebApplicationContext和 EmbeddedServletContainerCustomizerBeanPostProcessor类

 

 

 

 

 

 Finally: Questioning and Imagination

1. Java introduced java.lang.instrument in 1.5, so that a Java agent can be implemented , and a class can be changed by modifying the bytecode of a class through this agent. That is to say, a class can be customized, and a bean can be customized at a lower level. In fact, spring aop can choose JDK dynamic proxy and cglib dynamic proxy. By default, JAVA dynamic proxy is used. The essence of these two proxies is to modify bytecode and instrument ideas. Same. 

 

2. Most of the instrument application scenarios are to monitor the operation of the system, such as the invocation of the analysis service in the distributed system call chain.

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326986691&siteId=291194637