簡體   English   中英

Spring Boot 的 netty 上下文路徑

[英]netty context path for spring boot

我正在使用帶有 webflux 的 spring boot 並從 starter web 中刪除了嵌入式 tomcat 依賴項,我想為我的應用程序添加基本上下文路徑,有什么辦法嗎? 我需要這個,因為我在 kubernetes 集群后面有 ingrees 屬性,並且重定向是基於上下文路徑進行的。

    <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>

您不能同時使用 spring web 和 spring webflux 依賴項。 如果你這樣做,spring 將優先考慮 spring web 並且 webflux 過濾器不會在啟動時加載。

在啟動期間,spring 會嘗試為您創建正確的 ApplicationContext。 如此處所寫Spring boot Web Environment如果 Spring MVC (web) 在類路徑上,它將優先考慮此上下文。

Spring Boot 應用程序要么是傳統的 Web 應用程序,要么是 webflux 應用程序。 不能兩者兼而有之。

ContextPath 不是反應式編程中使用的東西,因此您必須過濾每個請求並重寫每個請求的路徑。

這應該可以工作,它是一個攔截每個請求的組件 webfilter,然后添加您在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 響應式應用程序加載時才有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM