SpringBoot Undertow:如何分派到工作线程

2024-04-06

我目前正在查看 springboot undertow,(对我来说)不太清楚如何将传入的 http 请求分派到工作线程以阻止操作处理。

看着班级Undertow 嵌入式 Servlet Container.class,看起来没有办法实现这种行为,因为唯一的 HttpHandler 是 ServletHandler,它允许 @Controller 配置

private Undertow createUndertowServer() {
    try {
        HttpHandler servletHandler = this.manager.start();
        this.builder.setHandler(getContextHandler(servletHandler));
        return this.builder.build();
    }
    catch (ServletException ex) {
        throw new EmbeddedServletContainerException(
                "Unable to start embdedded Undertow", ex);
    }
}

private HttpHandler getContextHandler(HttpHandler servletHandler) {
    if (StringUtils.isEmpty(this.contextPath)) {
        return servletHandler;
    }
    return Handlers.path().addPrefixPath(this.contextPath, servletHandler);

}

默认情况下,在 undertow 中,所有请求都由 IO-Thread 处理以进行非阻塞操作。 这是否意味着每个 @Controller 执行都将由非阻塞线程处理?或者是否有可以从 IO-THREAD 或 WORKER-THREAD 中选择的解决方案?

我尝试编写一个解决方法,但是这段代码非常难看,也许有人有更好的解决方案:

BlockingHandler.class

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BlockingHandler {

    String contextPath() default "/";

}

Undertow 初始化程序类

public class UndertowInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        configurableApplicationContext.addBeanFactoryPostProcessor(new UndertowHandlerPostProcessor());
    }

}

UndertowHandlerPostProcessor.class

public class UndertowHandlerPostProcessor implements BeanDefinitionRegistryPostProcessor {


    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(BlockingHandler.class));
        for (BeanDefinition beanDefinition : scanner.findCandidateComponents("org.me.lah")){

            try{
                Class clazz = Class.forName(beanDefinition.getBeanClassName());
                beanDefinitionRegistry.registerBeanDefinition(clazz.getSimpleName(), beanDefinition);
            } catch (ClassNotFoundException e) {
                throw new BeanCreationException(format("Unable to create bean %s", beanDefinition.getBeanClassName()), e);
            }
        }
    }


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //no need to post process defined bean
    }
}

覆盖 UndertowEmbeddedServletContainerFactory.class

public class UndertowEmbeddedServletContainerFactory extends  AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
        DeploymentManager manager = createDeploymentManager(initializers);
        int port = getPort();
        if (port == 0) {
            port = SocketUtils.findAvailableTcpPort(40000);
        }
        Undertow.Builder builder = createBuilder(port);

        Map<String, Object> handlers = applicationContext.getBeansWithAnnotation(BlockingHandler.class);
        return new UndertowEmbeddedServletContainer(builder, manager, getContextPath(),
            port, port >= 0, handlers);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

...

覆盖 UndertowEmbeddedServletContainer.class

public UndertowEmbeddedServletContainer(Builder builder, DeploymentManager manager,
                                        String contextPath, int port, boolean autoStart, Map<String, Object> handlers) {
    this.builder = builder;
    this.manager = manager;
    this.contextPath = contextPath;
    this.port = port;
    this.autoStart = autoStart;
    this.handlers = handlers;
}

private Undertow createUndertowServer() {
    try {
        HttpHandler servletHandler = this.manager.start();
        String path = this.contextPath.isEmpty() ? "/" : this.contextPath;
        PathHandler pathHandler = Handlers.path().addPrefixPath(path, servletHandler);
        for(Entry<String, Object> entry : handlers.entrySet()){
            Annotation annotation = entry.getValue().getClass().getDeclaredAnnotation(BlockingHandler.class);
            System.out.println(((BlockingHandler) annotation).contextPath());
            pathHandler.addPrefixPath(((BlockingHandler) annotation).contextPath(), (HttpHandler) entry.getValue());
        }

        this.builder.setHandler(pathHandler);
        return this.builder.build();
    }
    catch (ServletException ex) {
        throw new EmbeddedServletContainerException(
                "Unable to start embdedded Undertow", ex);
    }
}

将初始值设定项设置为应用程序上下文

public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).initializers(new UndertowInitializer()).run(args);
}

最后创建一个分派给工作线程的 Http Handler

@BlockingHandler(contextPath = "/blocking/test")
public class DatabaseHandler implements HttpHandler {

    @Autowired
    private EchoService echoService;

    @Override
    public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
        if(httpServerExchange.isInIoThread()){
            httpServerExchange.dispatch();
        }

        echoService.getMessage("my message");
    }

}

正如您所看到的,我的“解决方案”非常繁重,我非常感谢任何帮助来简化它。

谢谢


你不需要做任何事情。

Spring Boot 的默认 Undertow 配置使用 Undertow 的ServletInitialHandler https://github.com/undertow-io/undertow/blob/1.1.1.Final/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java在 Spring MVC 的前面DispatcherServlet。这个处理程序执行exchange.isInIoThread()检查并致电dispatch()如果需要的话 https://github.com/undertow-io/undertow/blob/1.1.1.Final/servlet/src/main/java/io/undertow/servlet/handlers/ServletInitialHandler.java#L160-L162.

如果你在你的@Controller,您会看到它在名为的线程上调用XNIO-1 task-n这是一个工作线程(IO 线程被命名为XNIO-1 I/O-n).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot Undertow:如何分派到工作线程 的相关文章

随机推荐