Maxwell_22 2024-12-12 11:21 采纳率: 50%
浏览 21
已结题

Springboot微服务架构网关配置问题

使用Eureka进行服务注册和发现,使用Spring Cloud Gateway进行网关配置。
项目结构如下:

img

全部run后,各微服务注册成功:

img

但是无法跨域访问(例如,可以向http://localhost:8082/api/driver/bill/1发送get请求,但向http://localhost:9999/api/driver/bill/1发送同样的请求,会报错404
相关的代码文件如下:
api-gateway中只写了配置文件application.yml:

spring:
  application:
    name: api-gateway  
  cloud:
    gateway:
      routes:
        - id: driver-management  
          uri: lb://driver-management 
          predicates:
            - Path=/api/driver/**  
        - id: passenger-management  
          uri: lb://passenger-management  
          predicates:
            - Path=/api/passenger/**  
        - id: billing-service 
          uri: lb://billing
          predicates:
            - Path=/bill/**
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowCredentials: true

    discovery:
      enabled: true 

server:
  port: 9999
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/ 

driver-service:
  base-url: http://localhost:8082
passenger-service:
  base-url: http://localhost:8081
billing-service:
  base-url: http://localhost:8083

driver-management的application.yml文件如下:

spring:
  application:
    name: driver-management
  datasource:
    url: jdbc:mysql://localhost:3306...//省略
    username: root
    password: *****
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    //not important
  cloud:
    discovery:
      enabled: true
      eureka:
        client:
          service-url:
            defaultZone: http://localhost:8761/eureka/  
    gateway:
      routes:
        - id: driver-management
          uri: lb://driver-management
          predicates:
            - Path=/api/driver/**
          filters:
            - StripPrefix=1

server:
  port: 8082

billing-service:
  base-url: http://localhost:8083
passenger-service:
  base-url: http://localhost:8081

另外两个微服务的配置文件类似。各微服务都配置了CorsConfig,可以从前端向它们的端口发送请求。
引入的依赖是

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway-mvc</artifactId>
        </dependency>

因为spring-cloud-starter-gateway好像版本不兼容。
请问是哪里有问题……

  • 写回答

2条回答 默认 最新

  • Maxwell_22 2024-12-13 01:35
    关注

    解决了,依赖必须是spring-cloud-starter-gateway而不能是spring-cloud-starter-gateway-mvc。这个模块中是这个就行,不必考虑其他微服务是否使用web依赖。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月21日
  • 已采纳回答 12月13日
  • 创建了问题 12月12日