春季启动的netty上下文路径

时间:2019-04-01 11:44:20

标签: spring-boot netty spring-webflux

我正在将spring boot与webflux一起使用,并从入门网站中删除了嵌入式tomcat依赖项,我想为我的应用程序添加基本上下文路径,有什么办法吗?我需要这个,因为我在kubernetes集群后面拥有grees属性,并且重定向是基于上下文路径进行的。

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
    <exclusion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
    </exclusions>

1 个答案:

答案 0 :(得分:1)

您不能同时使用spring web和spring webflux依赖项。如果这样做,spring将优先处理spring web,并且webflux过滤器将在启动时不加载。

在启动过程中,spring会尝试为您创建正确的ApplicationContext。如此处Spring boot Web Environment所述,如果Spring MVC(web)位于类路径中,它将优先处理此上下文。

Spring Boot应用程序要么是传统的Web应用程序,要么是webflux应用程序。不能两者都是。

ContextPath不是反应式编程中使用的东西,因此您必须过滤每个请求并重写每个请求的路径。

这应该可以工作,它是一个组件Web筛选器,它可以拦截每个请求,然后添加您在application.properties中定义的上下文路径

@Component
public class ContextFilter implements WebFilter {

    private ServerProperties serverProperties;

    @Autowired
    public ContextFilter(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        final String contextPath = serverProperties.getServlet().getContextPath();
        final ServerHttpRequest request = exchange.getRequest();
        if (!request.getURI().getPath().startsWith(contextPath)) {
            return chain.filter(
                    exchange.mutate()
                            .request(request.mutate()
                                            .contextPath(contextPath)
                                            .build())
                            .build());
        }
        return chain.filter(exchange);
    }
}

但这仅在您的应用程序作为Spring响应式应用程序加载时有效。

相关问题