3.1 Gateway之路由请求和转发

1.依赖坐标

xml 复制代码
		<!--网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--服务注册和发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--负载均衡-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>

2.路由属性

网关路由对应的Java类型是RouteDefinition,其中常见的属性有

属性 描述
id 路由唯一标识
uri 路由目标地址
predicates 路由断言,判断请求是否符合当前路由
filter 路由过滤器,对请求或响应做特殊处理

3.常用路由过滤器

过滤器 说明
AddRequestHeader 给当前请求添加一个请求头
RemoveRequestHeader 移除请求中的一个请求头
AddResponseHeader 给响应结果中添加一个响应头
RemoveResponseHeader 移除响应结果中的一个响应头
RewritePath 请求路径重写
StripPrefix 去除请求路径中的N段前缀

4.常见路由断言

名称 说明
After 是某个时间点后的请求
Before 是某个时间点之前的请求
Between 是某两个时间点之间的请求
Cookie 请求必须包含某些cookie
Header 请求必须包含某些header
Host 请求必须是访问某个域名
Method 请求方式必须是指定方式
Path 请求路径必须符合指定规则
Query 请求参数必须包含指定参数
RomoteAddr 请求者的IP必须是指定范围
Weight 权重处理
XForwarded Remote Addr 基于请求的来源IP做判断

5.配置文件

yaml 复制代码
spring:
  application:
    # 服务名称
    name: 服务名称
  cloud:
    # nacos配置
    nacos:
      # Nacos服务端地址
      server-addr: 端口:IP
      # 服务注册
      discovery:
        # 集群名称
        cluster-name: 集群名称
        # 命名空间ID
        namespace: 命名空间ID
        # 是否是临时实例,默认为true
        ephemeral: true
    # 网关配置
    gateway:
      # 路由配置
      routes:
        - id: 路由唯一标识
          uri: 路由目标地址 # 例如:lb://服务名
          predicates:
            - Path=请求路径 # 例如:/users/**
        - id: 路由唯一标识
          uri: 路由目标地址 # 例如:lb://服务名
          predicates:
            - 请求路径 # 例如:/orders/**
相关推荐
骚戴1 天前
n1n:从替代LiteLLM Proxy自建网关到企业级统一架构的进阶之路
人工智能·python·大模型·llm·gateway·api
骚戴1 天前
LLM API Gateway:LLM API 架构、AI 聚合与成本优化全解(2025深度指南)
人工智能·python·大模型·llm·gateway·api
serendipity_hky5 天前
【SpringCloud | 第4篇】Gateway网关统一入口
spring·spring cloud·微服务·gateway
库库林_沙琪马5 天前
4、Gateway
gateway
全靠bug跑5 天前
Spring Cloud Gateway 实战:统一鉴权与用户信息全链路透传
java·开发语言·gateway·拦截器
骚戴6 天前
架构设计之道:构建高可用的大语言模型(LLM) Enterprise GenAI Gateway
java·人工智能·架构·大模型·gateway·api
Maiko Star8 天前
Gateway网关拦截自定义header & 用户上下文打通实战
gateway·threadlocal
skywalk816311 天前
LLM API Gateway:使用Comate Spec Mode创建大模型调用中转服务器
服务器·人工智能·gateway·comate
我是小妖怪,潇洒又自在11 天前
springcloud alibaba(七)Gateway--服务网关
spring·spring cloud·gateway