官方简介
该项目提供了一个建立在Spring Ecosystem之上的API网关,包括:Spring 5,Spring Boot 2和Project Reactor。Spring Cloud Gateway旨在提供一种简单而有效的方式来对API进行路由,并为他们提供切面,例如:安全性,监控/指标 和弹性等。
官方工作原理介绍
客户端向
spring-cloud-gateway
请求
网关映射处理程序
(gateway handler mapping),如果确认请求与路由匹配,则将请求发送到
web处理程序
(gateway web handler),
web处理程序
通过特定于该请求的过滤器链处理请求,图中
filters
被虚线划分的原因是filters可以在发送代理请求之前(
pre filter
)或之后执行逻辑(
post filter
)。先执行所有
pre filter
逻辑,然后进行请求代理。在请求代理执行完后,执行
post filter
逻辑。
开始使用Spring-Cloud-Gateway
Spring Cloud Gateway依赖Spring Boot和Spring Webflux提供的Netty runtime,所以springboot必须在
2.0或者以上
,springcloud在
Finchley
以上,基本springcloud环境确认后,然后引入:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
路由配置
官网都是用的
yml
配置文件配置,与
properties
配置文件配置稍有不同,我这里全部使用
properties
配置文件配置。
直接使用注册中心路由配置
#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true
#服务路由名小写
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
指定服务配置
#设置路由id
spring.cloud.gateway.routes[0].id=auth-service
#设置路由的uri
spring.cloud.gateway.routes[0].uri=lb://auth-service
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates[0]= Path=/auth/**
spring.cloud.gateway.routes.predicates
:路由断言,配置时必须得有一项,不一定是
Path
;
spring.cloud.gateway.routes.uri
:配置路由uri,"lb://‘serviceId’"前代表路由的服务,同时也可以是一个url
编码服务配置
@Configuration
public class RoutesConfiguration {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes().route(predicateSpec ->
predicateSpec.path("/auth/**").uri("lb://auth-service").id("auth-service")
).build();
}
}