Spring Cloud 之 Gateway(springcloud五大组件面试题)
ztj100 2024-10-29 18:20 36 浏览 0 评论
一、Gateway 和 Zuul 的区别
Zuul 基于servlet 2.5 (works with 3.x),使用阻塞API。它不支持任何长期的连接,如websocket。
Gateway建立在Spring Framework 5,Project Reactor 和Spring Boot 2 上,使用非阻塞API。支持Websocket,因为它与Spring紧密集成,所以它是一个更好的开发者体验。
为什么 Spring Cloud 最初选择了使用 Netflix 几年前开源的 Zuul 作为网关,之后又选择了自建 Gateway 呢?有一种说法是,高性能版的 Zuul2 在经过了多次跳票之后,对于 Spring 这样的整合专家可能也不愿意再继续等待,所以 Spring Cloud Gateway 应运而生。
本文不对 Spring Cloud Gateway 和 Zuul 的性能作太多赘述,基本可以肯定的是 Gateway 作为现在 Spring Cloud 主推的网关方案, Finchley 版本后的 Gateway 比 zuul 1.x 系列的性能和功能整体要好。
二、快速入门
我们来搭建一个基于 Eureka 注册中心的简单网关,不对 Gateway 的全部功能做过多解读,毕竟官方文档已经写的很详细了,或者可以阅读中文翻译文档。
SpringBoot 版本号:2.1.6.RELEASE
SpringCloud 版本号:Greenwich.RELEASE
1. pom.xml
<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-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
- spring-cloud-starter-gateway:Spring Cloud Gateway 的启动类
- spring-cloud-starter-netflix-hystrix:Hystrix 作为网关的熔断方案
- spring-cloud-starter-netflix-eureka-client:将网关纳入 Eureka 注册中心管理
- spring-boot-starter-data-redis-reactive:限流方案,Spring Cloud Gateway 默认以 redis 实现限流
- spring-boot-starter-actuator:用来监控 Gateway 的路由信息。
2. application.yml
spring:
application:
name: cloud-gateway
redis:
host: 127.0.0.1
timeout: 3000
password: xxxx
jedis:
pool:
max-active: 8
max-idle: 4
cloud:
gateway:
enabled: true
metrics:
enabled: true
discovery:
locator:
enabled: true
routes:
# 普通服务的路由配置
- id: cloud-eureka-client
uri: lb://cloud-eureka-client
order: 0
predicates:
- Path=/client/**
filters:
# parts 参数指示在将请求发送到下游之前,要从请求中去除的路径中的节数。比如我们访问 /client/hello,调用的时候变成 http://localhost:2222/hello
- StripPrefix=1
# 熔断器
- name: Hystrix
args:
name: fallbackcmd
# 降级处理
fallbackUri: forward:/fallback
# 限流器
# 这定义了每个用户 10 个请求的限制。允许 20 个突发,但下一秒只有 10 个请求可用。
- name: RequestRateLimiter
args:
# SPEL 表达式获取 Spring 中的 Bean,这个参数表示根据什么来限流
key-resolver: '#{@ipKeyResolver}'
# 允许用户每秒执行多少请求(令牌桶的填充速率)
redis-rate-limiter.replenishRate: 10
# 允许用户在一秒内执行的最大请求数。(令牌桶可以保存的令牌数)。将此值设置为零将阻止所有请求。
redis-rate-limiter.burstCapacity: 20
# websocket 的路由配置
- id: websocket service
uri: lb:ws://serviceid
predicates:
- Path=/websocket/**
management:
endpoints:
web:
exposure:
# 开启指定端点
include: gateway,metrics
eureka:
client:
service-url:
defaultZone: http://user:password@localhost:1111/eureka/
- spring.redis.*: redis 相关配置是为了实现 Gateway 的限流方案。
- eureka.client.*:eureka 注册中心信息。
- spring.cloud.gateway.discovery.locator.enabled:将网关配置为基于使用兼容 DiscoveryClient 注册中心注册的服务来创建路由。
- spring.cloud.gateway.routes.*:配置路由信息
- id:路由唯一标识
- uri:路由转发地址,以 lb 开头的路由,会由 ribbon 处理,转发到 cloud-eureka-client 的服务处理。也可配置成 http 的单机路由 — http://localhost:2222。
- order:路由执行顺序(也可理解成过滤器的执行顺序),执行顺序是从小到大执行,较高的值被解释为较低的优先级。
- predicates:路由断言,匹配访问路径为 "/client/**" 的请求。
- filters:网关的过滤器配置
- management.endpoints.web.exposure.include:暴露 actuator 可以访问的端点
- /actuator/gateway/routes 查看路由列表
- /actuator/gateway/globalfilters 检索全局路由 — 对所有路由生效
- /actuator/gateway/routefilters 检索局部路由 — 可配置只对单个路由生效
- /actuator/gateway/refresh 清理路由缓存
- /actuator/metrics/gateway.requests 获得路由请求数据
3. GatewayApplication.java
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
/**
* 限流的键定义,根据什么来限流
*/
@Bean
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
}
三、过滤器
Spring Cloud Gateway 同 Zuul 类似,有 “pre” 和 “post” 两种方式的 filter。客户端的请求先经过 “pre” 类型的 filter,然后将请求转发到具体的业务服务,收到业务服务的响应之后,再经过“post”类型的filter处理,最后返回响应到客户端。
与 Zuul 不同的是,filter 除了分为 “pre” 和 “post” 两种方式的 filter 外,在 Spring Cloud Gateway 中,filter 从作用范围可分为另外两种,一种是针对于单个路由的 gateway filter,它需要像上面 application.yml 中的 filters 那样在单个路由中配置;另外一种是针对于全部路由的global gateway filter,不需要单独配置,对所有路由生效。
全局过滤器
我们通常用全局过滤器实现鉴权、验签、限流、日志输出等。
通过实现 GlobalFilter 接口来自定义 Gateway 的全局过滤器;通过实现 Ordered 接口或者使用 @Order 注解来定义过滤器的执行顺序,执行顺序是从小到大执行,较高的值被解释为较低的优先级。
@Bean
@Order(-1)
public GlobalFilter a() {
return (exchange, chain) -> {
log.info("first pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("third post filter");
}));
};
}
@Bean
@Order(0)
public GlobalFilter b() {
return (exchange, chain) -> {
log.info("second pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("second post filter");
}));
};
}
@Bean
@Order(1)
public GlobalFilter c() {
return (exchange, chain) -> {
log.info("third pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("first post filter");
}));
};
}
优先级最高的 filter ,它的 “pre” 过滤器最先执行,“post” 过滤器最晚执行。
局部过滤器
我们来定义一个 “pre” 类型的局部过滤器:
@Component
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
public PreGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
// grab configuration from Config object
return (exchange, chain) -> {
//If you want to build a "pre" filter you need to manipulate the
//request before calling chain.filter
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
//use builder to manipulate the request
ServerHttpRequest request = builder.build();
return chain.filter(exchange.mutate().request(request).build());
};
}
public static class Config {
//Put the configuration properties for your filter here
}
}
其中,需要的过滤器参数配置在 PreGatewayFilterFactory.Config 中。然后,接下来我们要做的,就是把局部过滤器配置在需要的路由上,根据 SpringBoot 约定大于配置的思想,我们只需要配置 PreGatewayFilterFactory.java 中,前面的参数就行了,即
spring:
cloud:
gateway:
routes:
- id: cloud-eureka-client
uri: lb://cloud-eureka-client
order: 0
predicates:
- Path=/client/**
filters:
- pre
tips:可以去阅读下 Gateway 中默认提供的几种过滤器,比如 StripPrefixGatewayFilterFactory.java 等。
四、动态路由
Spring Cloud Gateway 实现动态路由主要利用 RouteDefinitionWriter 这个 Bean:
public interface RouteDefinitionWriter {
Mono<Void> save(Mono<RouteDefinition> route);
Mono<Void> delete(Mono<String> routeId);
}
之前翻阅了网上的一些文章,基本都是通过自定义 controller 和出入参,然后利用 RouteDefinitionWriter 实现动态网关。但是,我在翻阅 Spring Cloud Gateway 文档的时候,发现 Gateway 已经提供了类似的功能:
@RestControllerEndpoint(id = "gateway")
public class GatewayControllerEndpoint implements ApplicationEventPublisherAware {
/*---省略前面代码---*/
@PostMapping("/routes/{id}")
@SuppressWarnings("unchecked")
public Mono<ResponseEntity<Void>> save(@PathVariable String id, @RequestBody Mono<RouteDefinition> route) {
return this.routeDefinitionWriter.save(route.map(r -> {
r.setId(id);
log.debug("Saving route: " + route);
return r;
})).then(Mono.defer(() ->
Mono.just(ResponseEntity.created(URI.create("/routes/"+id)).build())
));
}
@DeleteMapping("/routes/{id}")
public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
return this.routeDefinitionWriter.delete(Mono.just(id))
.then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())))
.onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
}
/*---省略后面代码---*/
}
要创建一个路由,发送POST请求 /actuator/gateway/routes/{id_route_to_create},参数为JSON结构,具体参数数据结构:
{
"id": "first_route",
"predicates": [{
"name": "Path",
"args": {"_genkey_0":"/first"}
}],
"filters": [],
"uri": "http://www.uri-destination.org",
"order": 0
}]
要删除一个路由,发送 DELETE请求 /actuator/gateway/routes/{id_route_to_delete}
相关推荐
- Win10预览版10532已知问题汇总(微软win11正式版已知问题一览)
-
IT之家讯微软已向Insider用户推送了Win10预览版10532更新,本次更新对右键菜单、《Windows反馈》应用以及Edge浏览器进行了改进。除此之外还包含一些Bug,汇总如下,有意升级Wi...
- Gabe Aul正测试Win10 Mobile 10532,Insider用户还需等
-
IT之家讯本月中旬微软向Insider用户推送了Win10Mobile预览版10512,该版本修复了一些Bug,增强了系统稳定性,但依然存在一些问题。今天,微软Insider项目负责人GabeAu...
- 微软开始推送Win10预览版10532快速版更新
-
8月28日消息,刚才,微软推送了Win10Build10532快速版,修复了之前的Bug,并带来了三项改进。主要来说,这次的更新改进了右键菜单的UI,使其更具Modern风格(见上图)。此外,更新...
- Win10预览版10532更新内容大全(windows10更新预览版)
-
IT之家讯今天凌晨微软向Insider用户推送了Win10预览版10532快速版更新,本次更新主要带来了三处改进,汇总如下:o改进右键菜单,外观更加Modern。这是基于网友要求界面一致的反馈做出...
- 无法升级Win10预览版10532?也许Hyper-V在搞鬼
-
根据IT之家网友的反映,安装了微软虚拟机Hyper-V的Win10预览版用户无法成功升级Build10532版本,安装过程中会被要求回滚系统。很多朋友在尝试关闭虚拟机之后重启安装程序,结果仍然无法顺...
- Win10预览版10532界面兴起“酷黑”风潮
-
Win10预览版10532的界面改动还是较为明显的,主要体现在右键菜单上面。总体来看,该版本的右键菜单间距更宽,视觉上更大气,操作上更便于触控。具体来说,任务栏右键菜单的变化最为明显。除了增加选项的宽...
- Win10预览版10532上手图集(windows10预览版下载)
-
IT之家讯8月28日,微软今天推送了Win10预览版10532快速版更新,在该版本中,微软主要是加强细节上调整,并且主要是增强Edge浏览器性能等。在Windows10预览版10532中,微软改进了...
- Win10预览版10532上手视频亮点演示
-
IT之家讯8月28日消息,今天凌晨微软向WindowsInsider快速通道用户推送了Win10预览版10532。在Windows10预览版10532中,微软改进了右键菜单,外观更加现代化。另外还...
- 第二篇 前端框架Vue.js(vue前端框架技术)
-
前端三大核心是网页开发的基础,Vue则是基于它们构建的“生产力工具”。通俗理解就是HTML是化妆的工具如眉笔,CSS是化妆品如口红,JavaScript是化妆后的互动,而Vue就是化妆助手。有了化妆工...
- 基于SpringBoot + vue2实现的旅游推荐管理系统
-
项目描述...
- 基于Vue以及iView组件的后端管理UI模板——iview-admin
-
介绍iView-admin是一套后端管理界面模板,基于Vue2.0,iView(现在为ViewUI)组件是一套完整的基于Vue的高质量组件库,虽然Github上有一套非常火的基于ElementUI...
- 别再说你会SPA开发了,这5个核心你真的搞懂了吗?
-
前言此spa非彼spa,不是你所熟知的spa。你所熟知的spa作者肯定是没有你熟悉的。我们这里指的是在前端开发中的一种模型,叫作单页应用程序,顾名思义,就是整个项目只有一个页面,而页面中的内容是动态的...
- React.js Top20面试题(react.js中文官网)
-
概述作为React开发者,对框架的关键概念和原则有扎实的理解是很重要的。考虑到这一点,我整理了一份包含20个重要问题的清单,每个React开发者都应该知道,无论他们是在面试工作还是只是想提高技能。...
- 美媒:特朗普签署行政令后,FBI又发现约2400份、总计超14000页涉肯尼迪遇刺案文件
-
来源:环球时报新媒体1月23日特朗普下令公布肯尼迪遇刺案相关机密文件图源:美媒综合福克斯新闻网和Axios网站10日报道,在总统特朗普签署行政令,要求公布“肯尼迪遇刺案”相关政府机密文件之后,美国...
- 2021 年 Node.js 开发人员学习路线图
-
Node.js自发布以来,已成为业界重要破局者之一。Uber、Medium、PayPal和沃尔玛等大型企业,纷纷将技术栈转向Node.js。Node.js支持开发功能强大的应用,例如实时追踪...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Win10预览版10532已知问题汇总(微软win11正式版已知问题一览)
- Gabe Aul正测试Win10 Mobile 10532,Insider用户还需等
- 微软开始推送Win10预览版10532快速版更新
- Win10预览版10532更新内容大全(windows10更新预览版)
- 无法升级Win10预览版10532?也许Hyper-V在搞鬼
- Win10预览版10532界面兴起“酷黑”风潮
- Win10预览版10532上手图集(windows10预览版下载)
- Win10预览版10532上手视频亮点演示
- 第二篇 前端框架Vue.js(vue前端框架技术)
- 基于SpringBoot + vue2实现的旅游推荐管理系统
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)