关于学习SpringCloud的整理2
4. Spring Cloud Gateway
- 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组件的核心是一系列的过滤器.
4.1 核心概念
- 过滤器(Filter) 一个标准的Spring WebFilter。 Spring Cloud Gateway中的Filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理
- 断言(Predicate) Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的
ServerWebExchange。Spring Cloud Gateway的断言函数允许开发者去定义匹配来自于HTTP Request中的
任何信息比如请求头和参数。 - 路由(Route) 路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言为真,说明请求URL和配置路由匹配。
以下是一些配置案例
server:
port: 8086
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: user-service-route
代理的服务地址
#uri: HTTP://127.0.0.1:9091
uri: lb://bill-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 添加请求路径的前缀
- StripPrefix=1
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 # 重试多少次服务
4.2 执行生命周期
Spring Cloud Gateway 的 Filter 的生命周期也类似Spring MVC的拦截器有两个:“pre” 和 “post”。“pre”和 “post”分别会在请求被执行前调用和被执行后调用
4.3 自定义过滤器
分为局部过滤器和全局过滤器
4.3.1 局部过滤器
```java
@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;
}
}
}
并且配置文件添加
- MyParam=name
4.3.2 全局过滤器
@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;
}
}
4.4 跨域配置
globalcors:
corsConfigurations:
‘[/**]’:
#allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- “http://docs.spring.io”
allowedMethods: - GET
4.5 Gateway与Feign的区别
Gateway 作为整个应用的流量入口,接收所有的请求,如PC、移动端等,并且将不同的请求转- 发至不同的处理微服务模块,其作用可视为nginx;大部分情况下用作权限鉴定、服务端流量控制.
Feign 则是将当前微服务的部分服务接口暴露出来,并且主要用于各个微服务之间的服务调用.
5.配置中心
- 在分布式系统中,由于服务数量非常多,配置文件分散在不同的微服务项目中,管理不方便。为了方便配置文件集中管理,需要分布式配置中心组件。在Spring Cloud中,提供了Spring Cloud Config,它支持配置文件放在配置服务的本地,也支持放在远程Git仓库(GitHub、码云)。
使用方法
- 创建文件
配置文件的命名方式:{application}-{profile}.yml 或 {application}-{profile}.properties
application为应用名称
profile用于区分开发环境,测试环境、生产环境等.
如bill-dev.yml,表示用户微服务开发环境下使用的配置文件。 - 配置中心配置参数
server:
port: 12000
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://gitee.com/lxsong77/lxs-config.git
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka - 配置中心启动类添加注解 @EnableConfigServer
- 服务或组件从配置中心获取配置
spring:
cloud:
config:
#要与仓库中的配置文件的application保持一致
name: user
#要与仓库中的配置文件的profile保持一致
profile: dev
#要与仓库中的配置文件所属的版本(分支)一样
label: master
discovery:
#使用配置中心
enabled: true
#配置中心服务名
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
6.Spring Cloud Bus服务总线
前面已经完成了将微服务中的配置文件集中存储在远程Git仓库,并且通过配置中心微服务从Git仓库拉取配置文件, 当用户微服务启动时会连接配置中心获取配置信息从而启动用户微服务。 如果我们更新Git仓库中的配置文件,那用户微服务是否可以及时接收到新的配置信息并更新呢?这就使用到Spring Cloud Bus.
使用方法
- 修改配置中心配置参数
server:
port: 12000
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://gitee.com/lxsong77/lxs-config.git
#配置rabbitmq信息;如果是都与默认值一致则不需要配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
management:
endpoints:
web:
exposure:
#暴露触发消息总线的地址
include: bus-refresh - 改造用户服务
- spring:
cloud:
config:
#要与仓库中的配置文件的application保持一致
name: user
#要与仓库中的配置文件的profile保持一致
profile: dev
#要与仓库中的配置文件所属的版本(分支)一样
label: master
discovery:
#使用配置中心
enabled: true
#配置中心服务名
service-id: config-server
#配置rabbitmq信息;如果是都与默认值一致则不需要配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
测试
第一步:依次启动注册中心 eureka-server 、配置中心 config-server 、用户服务 user-service
第二步:访问用户微服务http://localhost:9091/user/7;查看IDEA控制台输出结果
第三步:修改Git仓库中配置文件 user-dev.yml 的 test.name 内容
第四步:使用Postman或者RESTClient工具发送POST方式请求访问地址
- 最后附上SpringCloud完整体系架构图