Spring Cloud Gateway网关路由配置

Spring Cloud Gateway 配置使用 lb:// 协议时,需依赖以下组件:

核心依赖

‌Spring Cloud Gateway 依赖‌
需添加 spring-cloud-starter-gateway 依赖,用于启用网关功能。 ‌
 
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

服务注册中心依赖‌

若使用 lb:// 格式(即服务发现模式),需引入服务注册中心组件,例如Nacos 或 Eureka 的 Spring Cloud 启动器:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

负载均衡器依赖‌

需引入 spring-cloud-starter-loadbalancer 依赖,用于实现服务发现和负载均衡:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

配置要求

‌服务发现配置‌:确保 Nacos/Eureka 等服务注册中心已正确配置,且服务已注册。 ‌
‌路由配置示例‌:
# Tomcat
server:
  port: 8080

# Spring
spring:
  application:
    # 应用名称
    name: test-gateway
  profiles:
    # 环境配置
    active: dev
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        # 系统模块
        - id: test-system
          uri: lb://test-system
          predicates:
            - Path=/system/**
          filters:
            - StripPrefix=1
 
技术博主:AlanLee
posted @ 2025-10-26 15:49  AlanLee-Java  阅读(12)  评论(0)    收藏  举报