4、Gateway

Spring Cloud Gateway主要功能:

  • 反向代理
  • 认证鉴权
  • 流量控制
  • 熔断
  • 日志监控

官方解释:

客户端SpringCloud Gateway发出请求,然后在Gateway Handler Mapping中找到与之请求相匹配的路由,将其发送到Gateway Web Handler,Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。

过滤器之间用虚线分开是因为过滤器可能会发在代理请求之前("pre")或之后("post")执行业务逻辑,这样,Filter在"pre"类型的过滤器可以做参数校验,权限校验,流量监控,日志输出,协议转换等;在"post"类型的过滤器可以做响应内容,响应头的修改,日志的输出,流量监控等有着非常重要的作用


一、安装

1、新建一个微服务

1.1、新建gateway子模块

1.2、引入依赖

gateway服务依赖

pom 复制代码
<dependencies>  
    <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>  
    <dependency>  
        <groupId>org.springframework.cloud</groupId>  
        <artifactId>spring-cloud-starter-gateway</artifactId>  
    </dependency>  
</dependencies>
2、配置服务

2.1、创建启动类

java 复制代码
@SpringBootApplication
public class MdxShopGateWayApplication {
    public static void main(String[] args) {
        SpringApplication.run(MdxShopGateWayApplication.class, args);
    }
}

2.2、创建application.yml配置文件

yml 复制代码
spring:  
  application:  
    name: gateway  
  cloud:  
    nacos:  
      server-addr: http://192.168.88.139:8848  
      discovery:  
        username: nacos  
        password: nacos  
  
server:  
  port: 80

二、配置路由规则

springcloud 提供了两种方式

  • 通过配置文件的方式进行配置
  • 通过编码的方式进行配置

1、配置文件

创建 application-route.yml 文件

application-route.yml:

yml 复制代码
spring:  
  cloud:  
    gateway:  
      routes:  
        - id: order-service  
          uri: lb://service-order #lb = load balancer(负载均衡)  
          predicates: # 断言  
            - Path=/order/**  
          order: 0 # 路由的优先级, 越小优先级越高(默认为0)  
        - id: product-service  
          uri: lb://service-product  
          predicates:  
            - Path=/product/**

记得在 application.yml 中引入:

yml 复制代码
spring:  
  profiles:  
    include: route
基础原理

路由断言主要用来判断路由的规则。

配置文件中写的断言规则只是字符串,这些字符串会被Predicate Factory读取并处理。

例如Path=/user/**是按照路径匹配,这个规则是由org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory类来处理。

像这样的断言工厂在SpringCloudGateway还有十几个:

名称 说明 示例
After 是某个时间点后的请求 - After=2022-01-20T14:32:27.789-07:00[Asia/Shanghai]
Before 是某个时间点之前的请求 - Before=2022-04-13T15:14:47.433+08:00[Asia/Shanghai]
Between 是某两个时间点之前的请求 - Between=2021-01-20T17:42:47.789-07:00[Asia/Shanghai], 2023-01-21T17:42:47.789-07:00[Asia/Shanghai]
Cookie 请求必须包含某些cookie - Cookie=chocolate
Header 请求必须包含某些header - Header=asd, cas
Host 请求必须是访问某个host(域名) - Host=baidu.com, jd.com
Method 请求方式必须是指定方式 - Method=GET,POST
Path 请求路径必须符合指定规则 - Path=/user/{params},/card/**
Query 请求参数必须包含指定参数 - Query=name, Jack
RemoteAddr 请求者的ip必须是指定范围 - RemoteAddr=192.168.1.1/24
Weight 权重处理

实际使用时,根绝业务要求选择使用即可。

不过一般来讲,最常用的是使用Path这种断言工厂,仅用它就能满足常见的需求了。

2、编码配置


三、过滤器

过滤器执行的顺序:

  1. 请求先 依次通过每个过滤器的前置过滤
  2. 然后 倒序的通过每个过滤器的后置过滤

常用的几个有:

名称 说明
AddRequestHeader 给当前请求添加一个请求头
RemoveRequestHeader 移除请求中的一个请求头
AddResponseHeader 给响应结果中添加一个响应头
RemoveResponseHeader 从响应结果中移除有一个响应头
RequestRateLimiter 限制请求的流量
RewritePath 进行路由转发

1、局部过滤器

2、全局过滤器

yml 复制代码
spring:
  cloud:
    gateway:
      routes:
        - id: user-service 
          uri: lb://userservice 
          predicates: 
          - Path=/user/**
      default-filters:      # 默认过滤器配置
        - AddRequestHeader=token, test  # 添加请求头

四、自定义全局路由过滤器

有时候SpringCloudGateWay提供的过滤器工厂不能满足自己的要求。

可能有时候需要在过滤时做一些其它的逻辑操作。

那么这时候可以选择使用java代码自定义全局过滤器。

代码示例:

java 复制代码
@Component  
@Slf4j  
public class RtGlobalFilter implements GlobalFilter, Ordered {  
    @Override  
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {  
        ServerHttpRequest request = exchange.getRequest();  
        ServerHttpResponse response = exchange.getResponse();  
        String requestURI = request.getURI().getPath();  
        long startTime = System.currentTimeMillis();  
        log.info("请求【{}】开始:时间:{}", requestURI, startTime);  
        // =========== 以上是前置逻辑 ===========  
        Mono<Void> filter = chain.filter(exchange).doFinally((result) -> {  
            // =========== 以下是后置逻辑 ===========            long endTime = System.currentTimeMillis();  
            log.info("请求【{}】结束时间:{},耗时:{}ms", requestURI, endTime, endTime - startTime);  
        }); // 放行  
  
  
        return filter;  
    }  
  
    @Override  
    public int getOrder() {  
        return 0;  
    }  
}

当有多个过滤器时,Order的值决定了过滤器的执行顺序。

数值越大优先级越低, 负的越多, 优先级越高。

主要有两种方式

1,如上述代码这样

2,使用 @Order 注解

五、全局跨域

只需要修改一下配置即可

yml 复制代码
spring:  
  cloud:  
    gateway:  
      globalcors:  
        cors-configurations:  
          '[/**]': # 匹配所有路径  
            allowed-origin-patterns: "*"  # 允许所有源  
            allowed-headers: "*"          # 允许所有请求头  
            allowed-methods: "*"          # 允许所有请求方法

请求就携带了 跨域的请求头

相关推荐
坐吃山猪3 天前
OpenClaw04_Gateway常见问题
网络·gateway·openclaw
三水不滴3 天前
利用SpringCloud Gateway 重试 + 降级解决第三方接口频繁超时问题,提升性能
经验分享·笔记·后端·spring·spring cloud·gateway
知识即是力量ol4 天前
微服务架构:从入门到进阶完全指南
java·spring cloud·微服务·nacos·架构·gateway·feign
j200103224 天前
Gateway—— 高级流量路由
gateway·k8s
笨蛋不要掉眼泪4 天前
Spring Cloud Gateway 核心篇:深入解析过滤器(Filter)机制与实战
java·服务器·网络·后端·微服务·gateway
笨蛋不要掉眼泪4 天前
Spring Cloud Gateway 扩展:全局跨域配置
java·分布式·微服务·架构·gateway
love530love6 天前
ZeroClaw Reflex UI完整搭建流程——ZeroClaw Gateway + LM Studio + Reflex 本地 AI 管理面板
人工智能·windows·gateway·lm studio·reflex·openclaw·zeroclaw
利刃大大8 天前
【SpringCloud】Gateway Filter Factories && 过滤器执行顺序 && 自定义过滤器
java·后端·网关·spring cloud·gateway
2401_834120878 天前
spring-cloud-kubernetes与SpringCloud Gateway
spring cloud·kubernetes·gateway
猫头虎8 天前
web开发常见问题解决方案大全:502/503 Bad Gateway/Connection reset/504 timed out/400 Bad Request/401 Unauthorized
运维·前端·nginx·http·https·gateway·openresty