Spring Cloud Gateway网关
1. 简介
Spring Cloud Gateway是Spring官网基于Spring 5.0、 Spring Boot 2.0、Project Reactor等技术开发的网关 服务。
Spring Cloud Gateway基于Filter链提供网关基本功能:安全、监控/埋点、限流等。
Spring Cloud Gateway为微服务架构提供简单、有效且统一的API路由管理方式。
Spring Cloud Gateway是替代Netflix Zuul的一套解决方案。
Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对 应的微服务。 Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息, 从而加强安全保护。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。
网关的核心功能是:过滤和路由
2. Gateway加入后的架构
不管是来自于客户端(PC或移动端)的请求,还是服务内部调用。一切对服务的请求都可经过网关,然后再 由网关来实现 鉴权、动态路由等等操作。Gateway就是我们服务的统一入口。
3.核心概念
- 路由(route) 路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言为 真,说明请求URL和配置路由匹配
- 断言(Predicate) Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的 ServerWebExchange。Spring Cloud Gateway的断言函数允许开发者去定义匹配来自于HTTP Request中的 任何信息比如请求头和参数。
- 过滤器(Filter) 一个标准的Spring WebFilter。 Spring Cloud Gateway中的Filter分为两种类型的Filter,分 别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理
4.建立实例
4.1 新建工程
打开 lxs-springcloud\lxs-gateway\pom.xml 文件修改为如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud</artifactId>
<groupId>com.lqh</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lqh-gateway</artifactId>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<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>
</dependencies>
</project>
4.2 编写启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
4.3 编写启动类
server:
port: 10010
spring:
application:
name: api-gateway
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
需要用网关来代理 bill-service 服务,先看一下控制面板中的服务状态 :
-
ip为:127.0.0.1
-
端口为:12123
修改 lqh-gateway\src\main\resources\application.yml 文件为
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:12123
# 路由断言,可以配置映射路径
predicates:
- Path=/bill/**
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
将符合 Path 规则的一切请求,都代理到 uri 参数指定的地址 本例中,我们将路径中包含有 /bill/** 开头的请求, 代理到http://127.0.0.1:12123
4.5 启动测试
访问的路径中需要加上配置规则的映射路径,我们访问:http://localhost:10010/bill/list
http://localhost:10010/bill/list -> http://localhost:12123/bill/list
5.面向服务的路由
在刚才的路由规则中,把路径对应的服务地址写死了!如果同一服务有多个实例的话,这样做显然不合理。 应该根 据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!
5.1. 修改映射配置,通过服务名称获取
修改 lqh-gateway\src\main\resources\application.yml 文件如下:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: bill-service-route
# uri: http://127.0.0.1:12123
uri: lb://bill-service
#路由断言,可以配置映射路径
predicates:
- Path=/bill/**
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
路由配置中uri所用的协议为lb时(以uri: lb://user-service为例),gateway将使用 LoadBalancerClient把 user-service通过eureka解析为实际的主机和端口,并进行ribbon负载均衡。
5.2启动测试
再次启动 lxs-gateway ,这次gateway进行代理时,会利用Ribbon进行负载均衡访问: http://localhost:10010/bill/list 日志中可以看到使用了负载均衡器
6. 路由前缀
客户端的请求地址与微服务的服务地址如果不一致的时候,可以通过配置路径过滤器实现路径前缀的添加和 去除。
提供服务的地址:http://127.0.0.1:12123/bill/list
- 添加前缀:对请求地址添加前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/list --> http://127.0.0.1:12123/bill/list 添加前缀路径/bill
- 去除前缀:将请求地址中路径去除一些前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/api/bill/list --> http://127.0.0.1:12123/bill/list
6.1. 添加前缀
在gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加;
修改 lqh-gateway\src\main\resources\application.yml 文件:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:12123
# 路由断言,可以配置映射路径
predicates:
- Path=/**
filters:
# 添加请求路劲的前缀
- PrefixPath=/bill
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
通过 PrefixPath=/xxx 来指定了路由要添加的前缀。 也就是:
- PrefixPath=/bill http://127.0.0.1:10010/list --> http://127.0.0.1:12123/bill/list
- PrefixPath=/bill/adb http://127.0.0.1:10010/list --> http://127.0.0.1:12123/bill/abc/list
6.2. 去除前缀
在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除; 修改 lqh-gateway\src\main\resources\application.yml 文件:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:12123
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 表示过滤1个路径, 2表示两个路径,以此类推
- StripPrefix=1
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
通过 StripPrefix=1 来指定了路由要去掉的前缀个数。如:路径 /api/user/1 将会被代理到 /user/1 。 也就是:
- StripPrefix=1 http://127.0.0.1:10010/api/bill/list --> http://127.0.0.1:12123/bill/list
- StripPrefix=2 http://127.0.0.1:10010/api/bill/list --> http://127.0.0.1:12123/list
以此类推
7. 过滤器
7.1. 简介
Gateway作为网关的其中一个重要功能,就是实现请求的鉴权。而这个动作往往是通过网关提供的过滤器来实现 的。前面的 路由前缀 章节中的功能也是使用过滤器实现的。
Gateway自带过滤器有几十个,常见自带过滤器有:
详细的说明参考官网: https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.1.RELEASE/single/spring-cloud-gateway.html#_gatewayfilter_factories
配置全局默认过滤器
这些自带的过滤器可以和使用 路由前缀 章节中的用法类似,也可以将这些过滤器配置成不只是针对某个路由;而 是可以对所有路由生效,也就是配置默认过滤器:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:12123
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 表示过滤1个路径, 2表示两个路径,以此类推
- StripPrefix=1
# 默认过滤器, 对所有路由都生效
default-filters:
- AddResponseHeader=X-Response-Foo, Bar
- AddResponseHeader=abc-myname,lxs
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
上述配置后,再访问 http://localhost:10010/api/bill/list 的话;那么可以从其响应中查看到如下信息:
过滤器类型:Gateway实现方式上,有两种过滤器;
-
局部过滤器:通过 spring.cloud.gateway.routes.filters 配置在具体路由下,只作用在当前路由上;
如果配置spring.cloud.gateway.default-filters 上会对所有路由生效也算是全局的过滤器;但是这些过滤器 的 实现上都是要实现GatewayFilterFactory接口。
-
全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。
7.2. 执行生命周期
这里的 pre 和 post 可以通过过滤器的 GatewayFilterChain 执行filter方法前后来实现
7.3. 使用场景
常见的应用场景如下:
- 请求鉴权:一般 GatewayFilterChain 执行filter方法前,如果发现没有访问权限,直接就返回空。
- 异常处理:一般 GatewayFilterChain 执行filter方法后,记录异常并返回。
- 服务调用时长统计: GatewayFilterChain 执行filter方法前后根据时间统计。
8. 自定义过滤器
8.1. 自定义局部过滤器
需求:
在过滤器(MyParamGatewayFilterFactory)中将http://localhost:10010/api/user/8?name=lxs中的参数name的 值获取到并输出到控制台;并且参数名是可变的,也就是不一定每次都是name;需要可以通过配置过滤器的时候 做到配置参数名。
在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的 值。
1) 编写配置类
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
public MyParamGatewayFilterFactory() {
super(Config.class);
}
public List<String> shortcutFieldOrder() {
return Arrays.asList("param");
}
@Override
public GatewayFilter apply(Config config) {
return ((exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
if(request.getQueryParams().containsKey(config.param)) {
request.getQueryParams().get(config.param).forEach((v) -> {
System.out.printf("--局部过滤器--获得参数 %s = %s ----",config.param, v);
});
}
return chain.filter(exchange); //执行请求
});
}
//读取过滤器配置的参数
public static class Config {
//对应配置在application.yml 配置文件中的过滤器参数名
private String param;
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
}
2)修改配置文件
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:12123
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 表示过滤1个路径, 2表示两个路径,以此类推
- StripPrefix=1
# 自定义过滤器
- MyParam=name
# 默认过滤器, 对所有路由都生效
default-filters:
- AddResponseHeader=X-Response-Foo, Bar
- AddResponseHeader=abc-myname,lxs
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
注意:自定义过滤器的命名应该为:***GatewayFilterFactory
测试访问:http://localhost:10010/api/user/7?name=lxs检查后台是否输出name和lxs;但是若访问 http://localhost:10010/api/user/7?name2=kaikeba 则是不会输出的
8.2. 自定义全局过滤器
需求:编写全局过滤器,在过滤器中检查请求中是否携带token请求头。如果token请求头存在则放行;如果token 为空或者不存在则设置返回的状态码为:未授权也不再执行下去。
在lxs-gateway工程编写全局过滤器类MyGlobalFilter
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("全部过滤器");
String token = exchange.getRequest().getHeaders().getFirst("token");
if (StringUtils.isBlank(token)){
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
//值越小,优先级越高,越先执行
return 0;
}
}
访问 http://localhost:10010/api/user/7
访问 http://localhost:10010/api/user/7?token=abc
9. Gateway跨域配置
一般网关都是所有微服务的统一入口,必然在被调用的时候会出现跨域问题。
跨域:在js请求访问中,如果访问的地址与当前服务器的域名、ip或者端口号不一致则称为跨域请求。若不解决则 不能获取到对应地址的返回结果。
如:从在http://localhost:9090中的js访问 http://localhost:9000的数据,因为端口不同,所以也是跨域请求
在访问Spring Cloud Gateway网关服务器的时候,出现跨域问题的话;可以在网关服务器中通过配置解决,允许哪 些服务是可以跨域请求的;具体配置如下:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: bill-service-route
uri: http://127.0.0.1:12123
predicates:
- Path=/bill/**
# filters:
# - StripPrefix=1
globalcors:
corsConfigurations:
'[/**]':
# allowedOrigins: *# 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- "http://localhost:63342"
allowedMethods:
- GET
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
说明
上述配置表示:可以允许来自 http://localhost:63342 的get请求方式获取服务数据。
allowedOrigins 指定允许访问的服务器地址,如:http://localhost:10000 也是可以的。
‘[/**]’ 表示对所有访问到网关服务器的请求地址
官网具体说明:https://cloud.spring.io/spring-cloud-static/spring-cloudgateway/2.1.1.RELEASE/multi/multi__cors_configuration.html