Spring Boot Undertow在同一个应用程序中添加阻塞处理程序和NIO处理程序

时间:2014-12-19 10:13:58

标签: spring-mvc spring-boot undertow

在我的previous question中(感谢@Andy Wilkinson)我发现所有传入undertowEmbeddedServletContainer的请求都是由工作线程处理(阻塞操作)。

根据Andy的说法,我尝试添加UndertowBuilderCustomizer以覆盖ServletInitializerHandler以使用非阻塞处理程序处理传入的请求。

@Bean
public UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory(){
    UndertowEmbeddedServletContainerFactory undertowEmbeddedServletContainerFactory = new UndertowEmbeddedServletContainerFactory();
    undertowEmbeddedServletContainerFactory.addBuilderCustomizers(new UndertowBuilderCustomizer() {

        @Override
        public void customize(Undertow.Builder builder) {
            builder.setHandler(new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    exchange.getResponseSender().send("test");
                }
            });
        }
    });
    return undertowEmbeddedServletContainerFactory;
}

在此自定义程序中,我为NIO处理程序设置了构建器rootHandler。 但是UndertowEmbeddedServletContainer在启动阶段使用ServletInitializerHandler

覆盖它
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);
    }
}

正如这个问题的标题所说:我试图同时拥有阻塞和非阻塞处理程序,其中阻塞处理程序通过@Controller注释进行管理,而NIO处理程序由Spring管理。

我找到了一个解决方案,但作为初学者,我不知道它是否是一个好的解决方案。

HandlerPath注释

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

    public String path() default "";

}

创建实现HttpHandler的bean

@Component
@HandlerPath(path = "/hello-nio")
public class HelloHandler implements HttpHandler{

    @Autowired
   HelloService helloService;

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getResponseSender().send(helloService.sayHello("Josselin"));
    }  
}

创建一个简单的控制器

@Controller
public class HelloController {

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello(){
        return "hello";
    }
}

创建一个实现ServletExtension的类

public class NonBlockingHandlerExtension implements ServletExtension{

    @Override
    public void handleDeployment(DeploymentInfo deploymentInfo, final ServletContext servletContext) {
        deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() {
            @Override
            public HttpHandler wrap(final HttpHandler handler) {

                WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
                Map<String, Object> handlers = ctx.getBeansWithAnnotation(HandlerPath.class);

                PathHandler rootHandler = new PathHandler();
                rootHandler.addPrefixPath("/", handler);
                for(Map.Entry<String, Object> handlerEntry : handlers.entrySet()){
                    if(handlerEntry.getValue() instanceof HttpHandler){
                        HttpHandler httpHandler = (HttpHandler) handlerEntry.getValue();
                        String path = httpHandler.getClass().getAnnotation(HandlerPath.class).path();
                        rootHandler.addPrefixPath(path, httpHandler);
                    }
                }
                return rootHandler;
            }
        });
    }
}

在此方法中,默认的ServletInitializer处理程序绑定到&#34; /&#34;上下文,并由spring管理,因此所有阻止请求都可以由@Controller(s)处理。 然后我尝试发现所有使用@HandlerPath注释的bean,然后根据prefixPath属性向rootHandler添加新的@HandlerPath.path

最后

创建目录META-INF.services

创建一个文件io.undertow.servlet.ServletExtension并添加一行:

org.me.undertow.NonBlockingHandlerExtension

结果

All就像魅力一样,绑定URL时会调用NIO处理程序,阻塞处理程序也是如此。

有人可以告诉我这个解决方案是否可以通过任何方式改进? 此外,由于NIO处理程序URL不是由Spring管理的,我想我必须使用globaleMethodSecurity并设置@PreAuthorize来保护NIO处理程序?

1 个答案:

答案 0 :(得分:0)

我最近遇到了类似的问题,我发现UndertowEmbeddedServletContainerFactory提供了addDeploymentInfoCustomizers(),可用于将自定义HttpHandler放在处理程序链的开头。

实施例

@Bean
public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory(RootHandler rootHandler) {
    UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();

    factory.addDeploymentInfoCustomizers(deploymentInfo ->
            deploymentInfo.addInitialHandlerChainWrapper(rootHandler::setNext));

    return factory;
}

示例RootHandler

@Component
public class RootHandler implements HttpHandler {

    private HttpHandler next;

    @Autowired
    public RootHandler(...) {
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        if (exchange.getRelativePath().startsWith("/service")) {
            handleServiceRequest(exchange);
        } else {
            next.handleRequest(exchange);
        }
    }

    private void handleServiceRequest(HttpServerExchange exchange) {

        // ...

        exchange.getResponseSender().send("OK");
    }

    public HttpHandler setNext(HttpHandler next) {
        this.next = next;
        return this;
    }
}