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/**
相关推荐
摘星编程5 天前
Nginx 502 Bad Gateway:从 upstream 日志到 FastCGI 超时复盘
网络·nginx·gateway·php-fpm·fastcgi
网硕互联的小客服5 天前
504 Gateway Timeout:服务器作为网关或代理时未能及时获得响应如何处理?
运维·服务器·gateway
Pierre_6 天前
通过SpringCloud Gateway实现API接口镜像请求(陪跑)网关功能
spring·spring cloud·gateway
kk在加油7 天前
智能门卫:Gateway
gateway
小安同学iter8 天前
Spring Cloud Gateway 网关(五)
java·开发语言·spring cloud·微服务·gateway
JAVA学习通8 天前
Spring Cloud ------ Gateway
java·spring cloud·gateway
weixin_4495687010 天前
访问Nginx 前端页面,接口报502 Bad Gateway
前端·nginx·gateway
yangmf204013 天前
LDAP 认证系列(四):Gateway LDAP 认证
大数据·elasticsearch·搜索引擎·gateway·ldap
银迢迢15 天前
SpringCloud微服务技术自用笔记
java·spring cloud·微服务·gateway·sentinel
孤狼程序员19 天前
【Spring Cloud 微服务】2.守护神网关Gateway
spring cloud·微服务·gateway