一、Gateway是什么?
SpringCloud Gateway是Spring Cloud电商商城定制开发的一个全新项目,基于Spring 5.0+Spring Boot 2.0和Project Reactor电商商城定制开发等技术开发的网关,电商商城定制开发它旨在为架构提供—电商商城定制开发种简单有效的统一的API电商商城定制开发路由管理方式,电商商城定制开发以及提供统一的路由方式且基于Filter链电商商城定制开发提供一些强大的过滤器功能和网关电商商城定制开发基本的功能。
SpringCloud Gateway作为Spring Cloud电商商城定制开发生态系统中的,电商商城定制开发目标是替代Zuul,在Spring Cloud 2.0电商商城定制开发以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 1.x非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架中的reactor-netty响应式编程组件实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。
SpringCloud Gateway的目标提供统一的路由方式且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。
Spring Cloud Gateway具有如下特性:
- 基于Spring Framework 5, Project Reactor和Spring Boot 2.0进行构建;
- 动态路由:能够匹配任何请求属性;
- 可以对路由指定 Predicate(断言)和Filter (过滤器);
- 集成Hystrix的断路器功能;
- 集成 Spring Cloud 服务发现功能;
- 易于编写的 Predicate(断言)和Filter (过滤器);
- 请求限流功能;
- 支持路径重写。
二、Gateway工作流程
2.1三大核心概念
- Route(路由):路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由;
- Predicate(断言):参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由;
- Filter(过滤):指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。
2.2工作流程
客户端向Spring Cloud Gateway发出请求。然后在Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到GatewayWeb Handler。
Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。
Filter在“pre”类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等,在“post”类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量监控等有着非常重要的作用。
核心逻辑:路由转发 + 执行过滤器链。
三、Gateway构建以及使用
1先创建gateway模块,在pom.xml中添加依赖。
<!--gateway--><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId></dependency>
- 1
- 2
- 3
- 4
- 5
注意:不能添加actuator及web等依赖。
2 在application.yml文件中编写对应配置。
server: port: 9527spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由 routes: - id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名 uri: http://localhost:8001 #匹配后提供服务的路由地址# uri: lb://cloud-payment-service #匹配后提供服务的路由地址 predicates: - Path=/payment/get/** # 断言,路径相匹配的进行路由 - Method=GET #对应发请求为GET - id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名# uri: http://localhost:8001 #匹配后提供服务的路由地址 uri: lb://cloud-payment-service #匹配后提供服务的路由地址 predicates: - Path=/payment/lb/** # 断言,路径相匹配的进行路由 - Method=GET# - After=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] #请求要在这个时间之后# - Before=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] #请求要在这个时间之前# - Between=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] , 2020-03-08T10:59:34.102+08:00[Asia/Shanghai] #请求要在两个时间之间# curl http://localhost:9527/payment/lb --cookie "username=zzyy"# - Cookie=username,zzyy #Cookie=cookieName,正则表达式# 请求头要有X-Request-Id属性并且值为整数的正则表达式 这个是直接在cmd中运行 curl http://localhost:9527/payment/lb --cookie "username=zzyy" -H "X-Request-Id:11"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
3主启动类
@SpringBootApplication@EnableEurekaClientpublic class Gateway9527Application { public static void main(String[] args) { SpringApplication.run(Gateway9527Application.class, args); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
新建一个模块测试。
1.在application.yml文件中编写端口就即可,该端口号就是上面对应uri的端口。
server: port: 8001
- 1
- 2
2.编写测试方法
CommonResult 自定义返回类,返回类型以及类中逻辑换成自己的
@RestController@RequestMapping("payment")public class PaymentController { /** * 测试方法 */ @GetMapping("get/{id}") public CommonResult<Payment> selectOne(@PathVariable("id") Long id) { return new CommonResult<Payment>(200, "select success serverPort:" + serverPort,id); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3.访问 http://localhost:8001/payment/get/32 出现值,则访问成功。
4.启动网关服务模块,然后访问 http://localhost:9527/payment/get/32 返回值,则成功。
实现Gateway动态路由方式:
实现动态路由需要注意的是uri的协议为lb,表示启用Gateway的负载均衡功能。
当服务提供者有多个时,Gateway会根据注册中心注册的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能)。
修改yml文件配置,开启动态路由,并配置微服务名:
在测试类中添加一个返回端口的方法。
/** * 端口号 */ @Value("${server.port}") private String serverPort; @GetMapping("lb") public String getPaymentLB() { return serverPort; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
启动eureka注册中心,启动服务提供者8001,8002(将8001复制一份改个端口),再启动9527网关。
访问:http://localhost:9527/payment/lb,不停刷新页面,会看见8001/8002两个端口切换。
手写网关配置
在网关模块添加,直接访问http://localhost:9527/guonei,会跳转到http://news.baidu.com/guonei新闻界面**。
/** * 手写网关配置 */@Configurationpublic class GateWayConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) { RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes(); routes.route("path_route_atguigu", r -> r.path("/guoji").uri("http://news.baidu.com/guonei")) .build(); return routes.build(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Gateway常用(断言)
Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础的一部分。
Spring Cloud Gateway包括许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个RoutePredicate工厂可以进行组合。
Spring Cloud Gateway创建Route 对象时,使用RoutePredicateFactory 创建 Predicate对象,Predicate 对象可以赋值给Route。Spring Cloud Gateway包含许多内置的Route Predicate Factories。
所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合,并通过逻辑连接。
可以查看官网
常用的Route Predicate Factory:
- The After Route Predicate Factory
- The Before Route Predicate Factory
- The Between Route Predicate Factory
- The Cookie Route Predicate Factory
- The Header Route Predicate Factory
- The Host Route Predicate Factory
- The Method Route Predicate Factory
- The Path Route Predicate Factory
- The Query Route Predicate Factory
- The RemoteAddr Route Predicate Factory
- The weight Route Predicate Factory
列举部分常用断言:
The After Route Predicate Factory:
spring: cloud: gateway: routes: - id: after_route uri: https://example.org predicates: #在这个时间之后生效 - After=2017-01-20T17:42:47.789-07:00[America/Denver]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
The Before Route Predicate Factory:
spring: cloud: gateway: routes: - id: before_route uri: https://example.org predicates: #在这个时间之前生效 - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
The Between Route Predicate Factory:
spring: cloud: gateway: routes: - id: between_route uri: https://example.org predicates: #在这两个时间之间生效 - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
The Cookie Route Predicate Factory:
Cookie Route Predicate需要两个参数,一个是Cookie name ,一个是正则表达式。
路由规则会通过获取对应的Cookie name值和正则表达式去匹配,如果匹配上就会执行路由,如果没有匹配上则不执行。
spring: cloud: gateway: routes: - id: cookie_route uri: https://example.org predicates: - Cookie=chocolate, zzyy
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
The Header Route Predicate Factory:
spring: cloud: gateway: routes: - id: header_route uri: https://example.org predicates: #两个参数:一个是属性名称和一个正则表达式,这个属性值和正则表达式匹配则执行。 - Header=X-Request-Id, \d+
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
The Method Route Predicate Factory:
spring: cloud: gateway: routes: - id: method_route uri: https://example.org predicates: #表示请求方式 - Method=GET,POST
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
总结
Predicate就是为了实现一组匹配规则,让请求过来找到对应的Route进行处理。
Gateway中Filter(过滤器)使用
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。
种类(具体种类查看官方文档),分为单一的和全局的:
GatewayFilter(单一) - 有31种
GlobalFilter(全局) - 有10种
自定义全局GlobalFilter:
两个主要接口:GlobalFilter、Ordered
作用:全局日志记录、统一网关鉴权
编写过滤器
@Component@Slf4jpublic class MyLogGateWayFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info("***********come in MyLogGateWayFilter: " + new Date()); // 获取请求参数中的 uname String uname = exchange.getRequest().getQueryParams().getFirst("uname"); if (uname == null) { log.info("*******用户名为null,非法用户,o(╥﹏╥)o"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } /** * 加载过滤器顺序,数字越小优先级越高 * @return */ @Override public int getOrder() { return 0; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
该类实现了GlobalFilter, Ordered类,重写了filter方法并编写对应的过滤规则,这里是过滤用户。
访问http://localhost:9527/payment/lb 会发现不能访问,访问http://localhost:9527/payment/lb?uname=abc 则成功。