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/**
相关推荐
147API16 小时前
部署 Claude Apps Gateway,先把登录、策略和上游这条链跑通
gateway
tryxr5 天前
Spring Cloud Gateway
java·开发语言·数据库·网关·spring cloud·gateway
Jay Kay6 天前
SGLang Model Gateway 特性详解(Cache-Aware 之外)
gateway·sglang
专注_每天进步一点点8 天前
SLB(绑定弹性公网ip)-gateway-业务pod,gateway上出现reset by peer,业务pod上没有reset by peer
服务器·tcp/ip·gateway
mashirro13 天前
gateway服启动输出台显示
gateway
豆瓣鸡15 天前
网关、服务 userId 透传
java·微服务·gateway
Sean‘21 天前
GitLab 升级后 502:Puma 反复重启问题处理记录
docker·gateway·gitlab
Hadoop_Liang1 个月前
使用Kubernetes Gateway API实现域名访问应用
容器·kubernetes·gateway
worilb1 个月前
Spring Cloud 学习与实践(9):Gateway + JWT 统一鉴权
学习·spring cloud·gateway
Dontla1 个月前
Kong Gateway(OSS)(Open Source Software)与 Kong Gateway(Enterprise)区别
gateway·kong