目录
一、Gateway简介
Gateway是在Spring生态系统之上构建的API网关服务,基于Spring5,SpringBoot2和Project Reactor等技术。
Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:熔断、限流、重试。
微服务架构中网关的位置
1.1 Spring Cloud Gateway特性:
- 基于Spring Framework5,Project Reactor 和Spring Boot2.0进行构建
- 动态路由:能够匹配任何请求属性
- 可以对路由指定Predicate(断言)和Filter(过滤器)
- 集成Hystrix的断路器功能
- 集成Spring Cloud服务发现功能
- 易于编写的Predicate(断言)和Filter(过滤器)
- 请求限流功能
- 支持路径重写
1.2 gateway的三大核心概念
- Route(路由):路由是构建网关的基本模块,它是由ID,目标URI,一些列的断言和过滤器组成,如果断言为true则匹配路由
- Predicate(断言):可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
- Filter(过滤):指的是Spring框架中gatewayFilter的实例,使用过滤器,可以在请求被路由前或之后对请求进行修改。
Web请求通过一些匹配条件,定位到真正服务节点,并在这个转发过程的前后,进行一些精细化控制。
Pridicate就是我们的匹配条件,filter可以理解为一个无所不能的拦截器。有了这两个元素,再加上目标url,就可以实现一个具体的路由了。
客户端向Spring Cloud Gateway 发出请求,然后在Gateway Handler Mapping中找到与请求相匹配的路由,将其转发到Gateway Web Handler,Handler再通过制定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。
过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前“pre”或之后“post”执行业务逻辑。Filter在“pre”类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等,在“post”类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量监控等有着非常重要的作用。
Gateway核心逻辑: 路由转发 + 执行过滤器链
二、 代码演示,新建项目cloud-gateway-gateway9527
2.1 pom文件
<dependencies>
<!--gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 注册服务-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入自己定义的api通用包-->
<dependency>
<groupId>com.diligentkong.springcloud</groupId>
<artifactId>cloud-api-common</artifactId>
<version>${project.version}</version>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.2 application.yml文件
server:
port: 9527
spring:
application:
name: cloud-gateway
eureka:
instance:
hostname: cloud-gateway-service
client:
#表示是否将自己注册进EurekaServer中 默认为true
register-with-eureka: true
#是否从Eureka Server抓取已有的注册信息,默认为true 单节点无所谓,集群必须设置为true 才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka
2.3 主启动类,业务类没有
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
public static void main(String[] args) {
SpringApplication.run(GateWayMain9527.class,args);
}
}
2.4 9527网关如何做路由映射?
我们想访问 cloud-provider-payment8001中的lb接口,但目前不想暴露8001端口,希望在8001外面套一层9527,application.yml中新增网关配置
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_routh #payment_routh 路由的ID,没有固定规则但要求唯一,建议配合服务名
uri: http://localhost:8001 #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** #断言 路径相匹配的进行路由
- id: payment_routh2
uri: http://localhost:8011
predicates:
- Path=/payment/lb/**
2.5 测试
启动7001 启动8001(cloud-provider-payment8001) 启动9527
访问http://localhost:8001/payment/get/1
http://localhost:9527/payment/get/1
结果如下:
Gateway网关路由有两种配置方式,
- 在配置文件yml中配置
- 代码中注入RouteLocator的Bean
我们来演示第二种方式,这个时候需要访问外网
业务需求:通过9527网关访问外网的百度新闻网址
2.6 新建一个配置类 config/GateWayConfig
@Configuration
public class GateWayConfig {
/**
* 配置了一个id为route-name的路由规则
* 当访问地址为http://localhost:9527/guonei时会自动转发到地址https://news.baidu.com/guonei
* @param routeLocatorBuilder
* @return
*/
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route_diligentkong",
r -> r.path("/guonei")
.uri("https://news.baidu.com/guonei")).build();
return routes.build();
}
}
启动9527,访问http://localhost:9527/guonei 就转到了https://news.baidu.com/guonei
以上存在的问题:yml的地址是写死的,
解决方案:通过为服务名实现动态路由
默认情况下gateway会根据注册中心注册的服务列表,以注册中心上服务名为路径创建 动态路由进行转发,从而实现动态路由的功能
需要注意的是 uri的协议为lb,表示启用gateway的负载均衡功能
启动cloud-provider-payment8001 cloud-provider-payment8002
修改9527的yml
cloud:
gateway:
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
routes:
- id: payment_routh #payment_routh 路由的ID,没有固定规则但要求唯一,建议配合服务名
#uri: http://localhost:8001 #匹配后提供服务的路由地址
uri: lb://cloud-payment-service #匹配后提供服务的路由地址
predicates:
- Path=/payment/get/** #断言 路径相匹配的进行路由
- id: payment_routh2
#uri: http://localhost:8011
uri: lb://cloud-payment-service
predicates:
- Path=/payment/lb/**
测试 ,启动eureka7001,服务提供者8001,8002,9527
访问http://localhost:9527/payment/lb
结果:8001/8002两个端口切换
三、Predicate的使用
Predicate是什么?首先看一下9527日志:
Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分。Spring Cloud Gateway包含许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个Route Predicate工厂可以进行组合。
Spring Cloud Gateway创建Route对象时,使用RoutePredicateFactory创建Predicate对象,Predicate对象可以赋值给Route。Spring Cloud Gateway包含了许多内置的Route Predicate Factories。
所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合,通过逻辑and。
说白了,Predicate就是为了实现一组匹配规则,让请求过来找对应的Route进行处理。
四、Filter的使用
Filter是什么
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。
Spring Cloud Gateway内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。
Spring Cloud Gateway的Filter 生命周期有两种 pre post
种类有两种 gatewayFilter 和GlobalFilter
常用的gatewayFilter:
自定义过滤器,作用:全局日志记录 统一网关鉴权
新建类 filter/MyLogGatewayFilter
@Component
@Slf4j
public class MyLogGatewayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("********************come in MyLogGatewayFilter: "+ new Date());
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if (uname == null){
log.info("***********用户名为null,非法用户,┭┮﹏┭┮");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
启动9527,访问
http://localhost:9527/payment/lb?uname=kong
http://localhost:9527/payment/lb