在同一个项目中实现Spring Cloud Gateway

dev*_*ysf 4 spring spring-boot microservices api-gateway spring-cloud-gateway

我在 Spring Boot 微服务中为其他微服务提供了一个 api,并且我想在这个微服务前面放置一个 spring-cloud-gateway。

我已经查看了著名的 spring 文档(https://spring.io/guides/gs/gateway/),但据我了解,它要求我在单独的项目中启动云网关。但我想在我的微服务中运行 RouteLocator bean。不是在单独的项目中,而是在同一个项目中。

当我在同一个项目中使用它时,我收到这样的警告

“在类路径中发现 Spring MVC,目前与 Spring Cloud Gateway 不兼容。请删除 spring-boot-starter-web 依赖项。”

后来,正如他在警告中所说,我删除了 spring-boot-starter-web 依赖项,甚至进入了其他项目,将它们从那里排除,如下所示

        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-boot-starter-web</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

这次我逻辑上得到了错误

“org.springframework.beans.factory.BeanDefinitionStoreException:无法处理配置类 [com.company Operations.Service OperationsApplication] 的导入候选者;嵌套异常为 org.spring..core.NestedIOException:无法加载类 [javax.servlet. Filter];嵌套异常是java.lang.ClassNotFoundException: javax.servlet.Filter”。

我们从应该提供Web api服务的项目中删除了核心库:D

那么,我可以在同一个项目中使用云网关吗?不使用的理由和逻辑是什么?

如果不可能在同一个项目中使用它,那么众所周知的网关实践应该如何,我应该在每个 api 微服务前面放置一个网关,还是应该在我的项目中拥有一个由多个 api 微服务组成的网关一个微服务?

saw*_*wim 5

您可以在同一个项目中启动 gateway,但这是一个基于 webflux 的项目。来自文档

Spring Cloud Gateway 基于 Spring Boot 2.x、Spring WebFlux 和 Project Reactor 构建。因此,当您使用 Spring Cloud Gateway 时,您所知道的许多熟悉的同步库(例如 Spring Data 和 Spring Security)和模式可能不适用。如果您不熟悉这些项目,我们建议您在使用 Spring Cloud Gateway 之前首先阅读他们的文档来熟悉一些新概念。

Spring Cloud Gateway 需要 Spring Boot 和 Spring Webflux 提供的 Netty 运行时。它不适用于传统的 Servlet 容器或构建为 WAR 时。

所以你应该使用spring-boot-starter-webflux而不是spring-boot-starter-web.

或者,如果您需要使用传统的 Spring MVC,请考虑使用Spring Netflix Zuul。该项目目前处于维护模式,Spring Gateway 是它的后继者,但它应该可以工作。