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

标签 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 found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency."

后来,正如他在警告中所说,我删除了 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>

这次我逻辑上报错了

"org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.company operations.Service operationsApplication]; nested exception is org.spring. .core.NestedIOException: Failed to load class [javax.servlet.Filter]; nested exception is java.lang.ClassNotFoundException: javax.servlet.Filter ".

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

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

如果不能在同一个项目中使用,gateway的大家熟知的做法应该如何,是应该在每个api微服务前面放一个gateway,还是应该在我的项目中单独一个gateway组成不止一种微服务?

最佳答案

您可以在同一个项目中启动网关,但这是一个基于 webflux 的项目。 来自 documentation

Spring Cloud Gateway is built on Spring Boot 2.x, Spring WebFlux, and Project Reactor. As a consequence, many of the familiar synchronous libraries (Spring Data and Spring Security, for example) and patterns you know may not apply when you use Spring Cloud Gateway. If you are unfamiliar with these projects, we suggest you begin by reading their documentation to familiarize yourself with some of the new concepts before working with Spring Cloud Gateway.

Spring Cloud Gateway requires the Netty runtime provided by Spring Boot and Spring Webflux. It does not work in a traditional Servlet Container or when built as a WAR.

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

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

关于spring - 在同一个项目中实现 Spring Cloud Gateway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66708646/

相关文章:

spring - MockRestServiceServer 未正确验证请求

java - 交易异常 : Transaction not successfully started

java - 如何在拥有 html、css 和 js 文件的情况下构建 Angular6 项目

java - 如何在 spring-boot 中的微服务中创建 Super/Base/Parent 类 - 在子类中扩展该类

java - 在 Spring Boot 服务中运行 H2 数据库多个实例

c# - Azure Service Fabric 参与者微服务

html - Bootstrap col-md 剪切标签的文字

java - Java EE/Jakarta EE 是否支持 Java 模块系统?是否可以使用 Java 模块系统制作 Web 应用程序?

node.js - 默认值Nodejs

Java Jackson 如何在自定义序列化程序中为对象使用默认序列化程序