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/**
相关推荐
lwb_01182 天前
SpringCloud——Gateway新一代网关
spring·spring cloud·gateway
你是人间五月天2 天前
gateway断言配置详解
gateway
weixin_387545642 天前
深入解析 AI Gateway:新一代智能流量控制中枢
人工智能·gateway
yuluo_YX16 天前
AI Gateway 介绍
人工智能·gateway
网硕互联的小客服19 天前
502 Bad Gateway:服务器作为网关或代理时收到无效响应处理方式
运维·服务器·gateway
sevevty-seven19 天前
什么是Gateway
gateway
秋の花19 天前
【GateWay】和权限验证
java·gateway
欧先生^_^21 天前
org.springframework.cloud.gateway 组件解释
gateway
jarenyVO22 天前
Spring Cloud Gateway 全面学习指南
java·gateway
保持学习ing24 天前
微服务--Gateway网关
java·网关·微服务·gateway