java - spring boot 的 netty 上下文路径

标签 java spring-boot netty spring-webflux

我正在使用带有 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 响应式(Reactive)应用程序加载时才有效。

关于java - spring boot 的 netty 上下文路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55454322/

相关文章:

java - 如何处理年龄限制Youtube Data API 3.0

java - java.sql.Date 是否可以强制只向 Oracle Date 列插入年、月、日

java - 多次调用Netty解码器方法

java - 从字符串中删除重音

java - 如何在不是 Activity 的布局上暂时隐藏操作栏

java - 在 Java Spring Boot 中运行时更改 @Bean 的值

Spring MockMvc 失败 : No mapping found for HTTP request with URI

java - 如何在spring-boot中添加多个application.properties文件?

java - 如何减少网络垃圾的产生?

netty - 找不到 io.netty.resolver.dns.macos.MacOSDnsServerAddressStreamProvider