MST

星途 面试题库

面试题:微服务架构下Spring Cloud Gateway智能路由的基础配置

在基于Spring Cloud Gateway构建微服务智能路由时,如何配置一个简单的路径转发规则,将所有以/api/user开头的请求转发到名为user - service的微服务实例上?请写出关键的配置代码片段。
29.3万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

在Spring Cloud Gateway的application.yml配置文件中,可以这样配置:

spring:
  cloud:
    gateway:
      routes:
      - id: user_route
        uri: lb://user-service
        predicates:
        - Path=/api/user/**

上述配置中:

  • id 是路由的唯一标识。
  • uri 使用lb://前缀表示基于负载均衡(LoadBalancer)的方式转发到名为user-service的微服务实例,这要求微服务注册在服务注册中心(如Eureka、Consul等)。
  • predicates 中的Path表示匹配以/api/user开头的请求路径。