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: "*"          # 允许所有请求方法

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

相关推荐
lhrimperial2 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(一)
spring cloud·微服务·系统架构·gateway
lhrimperial2 天前
深入浅出Spring Cloud Gateway:从理论到企业级实践(二)
spring cloud·微服务·系统架构·gateway
ghostwritten3 天前
云原生流量治理新标准:Kubernetes Gateway API 部署实践指南
云原生·kubernetes·gateway
齐 飞3 天前
Spring Cloud Alibaba快速入门-Gateway
spring cloud·微服务·gateway
Linux运维技术栈3 天前
Gravitee Kafka Gateway 规范部署:HTTP API化封装与安全隔离实践
http·kafka·gateway
trayvontang5 天前
Spring Gateway核心概念、流程及原理
spring·gateway·spring gateway
trayvontang5 天前
Spring Gateway常用过滤器(限流、熔断等)
spring·gateway·spring gateway·gateway常用过滤器
Hello.Reader7 天前
Flink SQL Gateway 把 Flink SQL 变成“多客户端并发可用”的统一服务入口
sql·flink·gateway
ygqygq29 天前
Kubernetes Gateway API 与 Envoy Gateway 部署使用指南
kubernetes·gateway·envoy·ingress
weixin_439706259 天前
spring boot+nacos+gateway+sentinel的简单例子
spring boot·gateway·sentinel