简介
- 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服务注册中心。
网关的核心功能是:过滤和路由
核心概念
- 路由(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将会对请求和响应进行修改处理
快速入门
需求:通过网关系统lxs-gateway将包含有 /user 的请求路由到 http://127.0.0.1:9091/user/用户id
新建工程
打开 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/maven4.0.0.xsd">
<parent>
<artifactId>lxs-springcloud</artifactId>
<groupId>com.lxs</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>lxs-gateway</artifactId>
<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>
编写启动类
在lxs-gateway中创建 com.lxs.gateway.GatewayApplication
启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
编写配置
创建 lxs-gateway\src\main\resources\application.yml
文件,内容如下:
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
需要用网关来代理 user-service 服务
先看一下控制面板中的服务状态 :
- ip为:127.0.0.1
- 端口为:9091
修改 lxs-gateway\src\main\resources\application.yml 文件为:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: http://127.0.0.1:9091
# 路由断言,可以配置映射路径
# Path的映射在其它的微服务中上下文路径相同
predicates:
- Path=/user/**
eureka:
client:
service-url:
defaultZone: HTTP://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
将符合 Path 规则的一切请求,都代理到 uri 参数指定的地址
本例中,我们将路径中包含有 /user/** 开头的请求, 代理到http://127.0.0.1:9091
启动测试
访问的路径中需要加上配置规则的映射路径,我们访问:http://localhost:10010/user/7
http://localhost:10010/user/7 -> http://localhost:9091/user/7
面向服务的路由
在刚才的路由规则中,把路径对应的服务地址写死了!如果同一服务有多个实例的话,这样做显然不合理。 应该根据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!
修改映射配置,通过服务名称获取
修改 lxs-gateway\src\main\resources\application.yml 文件如下:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
# uri: HTTP://127.0.0.1:9091
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/user/**
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负载均衡。
启动测试
再次启动 lxs-gateway ,这次gateway进行代理时,会利用Ribbon进行负载均衡访问
路由前缀
客户端的请求地址与微服务的服务地址如果不一致的时候,可以通过配置路径过滤器实现路径前缀的添加和去除。
提供服务的地址:http://127.0.0.1:9091/user/8
-
添加前缀:对请求地址添加前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/8 --> http://127.0.0.1:9091/user/8 添加前缀路径/user
-
去除前缀:将请求地址中路径去除一些前缀路径之后再作为代理的服务地址;
http://127.0.0.1:10010/api/user/8 --> http://127.0.0.1:9091/user/8 去除前缀路径/api
添加前缀
在gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加;
修改 lxs-gateway\src\main\resources\application.yml
文件:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/**
filters:
# 添加请求路径的前缀
- PrefixPath=/user
eureka:
client:
service-url:
defaultZone: HTTP://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
通过 PrefixPath=/xxx
来指定了路由要添加的前缀。 也就是:
- PrefixPath=/user http://localhost:10010/8 --> http://localhost:9091/user/8
- PrefixPath=/user/abc http://localhost:10010/8 --> http://localhost:9091/user/abc/8
去除前缀
在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除;
修改 lxs-gateway\src\main\resources\application.yml
文件:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/user/**
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://localhost:10010/api/user/8 --> http://localhost:9091/user/8
- StripPrefix=2 http://localhost:10010/api/user/8 --> http://localhost:9091/8
以此类推
过滤器
Gateway作为网关的其中一个重要功能,就是实现请求的鉴权。而这个动作往往是通过网关提供的过滤器来实现的。前面的 路由前缀 章节中的功能也是使用过滤器实现的。
Gateway自带过滤器有几十个,常见自带过滤器有:
过滤器名称 | 说明 |
---|---|
AddRequestHeader | 对匹配上的请求加上Header |
AddRequestParameters | 对匹配上的请求路由添加参数 |
AddResponseHeader | 对从网关返回的响应添加Header |
StripPrefix | 对匹配上的请求路径去除前缀 |
详细的说明参考官网链接
配置全局默认过滤器
这些自带的过滤器可以和使用 路由前缀 章节中的用法类似,也可以将这些过滤器配置成不只是针对某个路由;而是可以对所有路由生效,也就是配置默认过滤器:
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/user/**
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
过滤器类型:Gateway实现方式上,有两种过滤器;
-
局部过滤器:通过 spring.cloud.gateway.routes.filters 配置在具体路由下,只作用在当前路由上;
如果配置spring.cloud.gateway.default-filters 上会对所有路由生效也算是全局的过滤器;但是这些过滤器 的 实现上都是要实现GatewayFilterFactory接口。
-
全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。
执行生命周期
Spring Cloud Gateway 的 Filter 的生命周期也类似Spring MVC的拦截器有两个:“pre” 和 “post”。“pre”和 “post” 分别会在请求被执行前调用和被执行后调用
这里的 pre 和 post 可以通过过滤器的 GatewayFilterChain 执行filter方法前后来实现
使用场景
- 请求鉴权:一般 GatewayFilterChain 执行filter方法前,如果发现没有访问权限,直接就返回空。
- 异常处理:一般 GatewayFilterChain 执行filter方法后,记录异常并返回。
- 服务调用时长统计: GatewayFilterChain 执行filter方法前后根据时间统计。
自定义过滤器
自定义局部过滤器
需求:
在过滤器(MyParamGatewayFilterFactory)中将http://localhost:10010/api/user/8?name=lxs中的参数name的 值获取到并输出到控制台;并且参数名是可变的,也就是不一定每次都是name;需要可以通过配置过滤器的时候做到配置参数名。
在application.yml中对某个路由配置过滤器,该过滤器可以在控制台输出配置文件中指定名称的请求参数的值。
编写过滤器
package com.lxs.gateway.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.HTTP.server.reactive.ServerHTTPRequest;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Component
public class MyParamGatewayFilterFactory extends
AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {
static final String PARAM_NAME = "param";
public MyParamGatewayFilterFactory() {
super(Config.class);
}
public List<String> shortcutFieldOrder() {
return Arrays.asList(PARAM_NAME);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
// http://localhost:10010/api/user/8?name=lxs config.param ==> name
//获取请求参数中param对应的参数名 的参数值
ServerHTTPRequest request = exchange.getRequest();
if(request.getQueryParams().containsKey(config.param)){
request.getQueryParams().get(config.param).forEach(value -> System.out.printf("------------局部过滤器--------%s = %s------", config.param, value));
}
return chain.filter(exchange);
};
}
public static class Config{
//对应在配置过滤器的时候指定的参数名
private String param;
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
}
修改配置文件
server:
port: 10010
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/user/**
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 则是不会输出的
自定义全局过滤器
需求:编写全局过滤器,在过滤器中检查请求中是否携带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("--------------全局过滤器MyGlobalFilter------------------");
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 1;
}
}
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,可以随意写
- id: user-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/user/**
filters:
# 表示过滤1个路径,2表示两个路径,以此类推
- StripPrefix=1
# 自定义过滤器
- MyParam=name
# 默认过滤器,对所有路由都生效
default-filters:
- AddResponseHeader=X-Response-Foo, Bar
- AddResponseHeader=abc-myname,lxs
globalcors:
corsConfigurations:
'[/**]':
#allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- "http://docs.spring.io"
allowedMethods:
- GET
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S
ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 0 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 0 # 重试多少次服务
说明
上述配置表示:可以允许来自 http://docs.spring.io 的get请求方式获取服务数据。
allowedOrigins 指定允许访问的服务器地址,如:http://localhost:10000 也是可以的。
‘[/**]’ 表示对所有访问到网关服务器的请求地址
官网具体说明:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.1.RELEASE/multi/multi__cors_configuration.html
Gateway与Feign的区别
- Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转- 发至不同的 处理微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制
- Feign 则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用