1.1 概述
Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor(响应式编程) 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。
Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 2.0之前的非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。
1.1.1 相关术语
Gateway 目标是替代 Zuul,所有基本特性差别不大,主要的区别,底层的通信框架。
1.2 入门
1.2.1 搭建环境
创建项目:test-gateway-2.1
修改pom,添加坐标
org.springframework.cloud
spring-cloud-starter-gateway
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
配置 yml文件:application.yml
#端口号
server:
port: 10010
spring:
application:
name: test-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #nacos服务地址
gateway:
discovery:
locator:
enabled: true #开启服务注册和发现的功能,自动创建router以服务名开头的请求路径转发到对应的服务
编写启动类
@SpringBootApplication
@EnableDiscoveryClient
public class TestGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(TestGatewayApplication.class, args);
}
}
1.2.2 测试
http://localhost:10010/service-consumer/feign/echo/abc
http://localhost:10010/service-provider/echo/abc
2.1 routes路由
2.1.2 路由匹配规则
gateWay的主要功能之一是转发请求,转发规则的定义主要包含三个部分
修改yml文件,添加
routes:
- id: consumer #自定义
uri: lb://service-consumer #访问路径
predicates: #断言
- Path=/consumer/**
filters: #过滤器
- StripPrefix=1
2.2.1 predicates 断言
在 Spring Cloud Gateway 中 Spring 利用 Predicate 的特性实现了各种路由匹配规则,有通过 Header、请求参数等不同的条件,来进行作为条件匹配到对应的路由。
简单来说, Predicate 就是一组匹配规则,方便请求过来时,匹配到对应的 Route 进行处理。
Spring Cloud GateWay 内置多种 Predicate ,如下:
实例1:通过请求参数匹配
spring:
cloud:
gateway:
routes:
- id: query
uri: http://www.czxy.com
predicates:
- Query=my,123
#访问路径,有参数my将转发到www.czxy.com
http://localhost:10010/?my=123
实例2:通过请求路径匹配
spring:
cloud:
gateway:
routes:
- id: path
uri: http://www.czxy.com
predicates:
- Path=/czxy/{flag}
#
http://localhost:10010/czxy/666
总结:
各种 Predicates 同时存在于同一个路由时,请求必须同时满足所有的条件才被这个路由匹配。
一个请求满足多个路由的断言条件时,请求只会被首个成功匹配的路由转发
7.3.3 Filter 网关过滤器
路由过滤器允许以某种方式修改传入的HTTP请求或传出HTTP响应。
实例1:跳过指定路径
spring:
cloud:
gateway:
routes:
- id: consumer
uri: lb://service-consumer
predicates:
- Path=/consumer/**
filters:
- StripPrefix=1
实例2:添加前缀
spring:
cloud:
gateway:
routes:
- id: PrefixPath
uri: lb://service-consumer
predicates:
- Path=/consumer/**
filters:
- StripPrefix=1
- PrefixPath=/feign
实例3:改写路径
spring:
cloud:
gateway:
routes:
- id: RewritePath
uri: lb://service-consumer
predicates:
- Path=/consumer/**
filters:
- RewritePath=/consumer(?/?.*), $\{segment}
到这里说明你已经学会了哦,努力学习!学无止境!!!