重写SpringCloudGateway路由查找算法,性能提升100倍!
如果你也在做SpringCloudGateway网关开发,希望这篇文章能给你带来一些启发
背景
先说背景,某油项目,通过SpringCloudGateway配置了1.6万个路由规则,实际接口调用过程中,会偶现部分接口从发起请求到业务应用处理间隔了大概5秒的时间,经排查后发现是SpringCloudGateway底层在查找对应的Route时采用了遍历+断言匹配的方式,路由规则太多时就会出现耗时太久的问题,对应的源码如下:
protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
return this.routeLocator
.getRoutes()
//individually filter routes so that filterWhen error delaying is not a problem
.concatMap(route -> Mono
.just(route)
.filterWhen(r -> {
// add the current route we are testing
exchange.getAttributes().put(GATEWAY_PREDICATE_ROUTE_ATTR, r.getId());
return r.getPredicate().apply(exchange);
})
//instead of immediately stopping main flux due to error, log and swallow it
.doOnError(e -> logger.error("Error applying predicate for route: "+route.getId(), e))
.onErrorResume(e -> Mono.empty())
)
// .defaultIfEmpty() put a static Route not found
// or .switchIfEmpty()
// .switchIfEmpty(Mono.<Route>empty().log("noroute"))
.next()
//TODO: error handling
.map(route -> {
if (logger.isDebugEnabled()) {
logger.debug("Route matched: " + route.getId());
}
validateRoute(route, exchange);
return route;
});
/* TODO: trace logging
if (logger.isTraceEnabled()) {
logger.trace("RouteDefinition did not match: " + routeDefinition.getId());
}*/
}
目标
找到了问题,就需要对这块路由查找的代码进行优化,我们分析了下路由规则,发现可以用请求方法Method+请求路径Path作为key,把对应的Route作为缓存值,通过ServerWebExchange直接命中对应的路由对象(这里要注意下,如果有同样的问题,需要根据实际情况设计缓存键,比如/person/**这种断言Path就不适用了),对应的路由规则如下:
{
"predicates": [
{
"args": {
"_genkey_0": "/v1/structuredData/serviceData/cestc_dportal/MH_GX_JS_SJCZQX3080"
},
"name": "Path"
},
{
"args": {
"_genkey_0": "GET"
},
"name": "Method"
}
],
"filters": [
{
"args": {
"_genkey_1": "/myapi/v1.0/zhyApi/getDataForGet",
"_genkey_0": "/v1/structuredData/serviceData/cestc_dportal/MH_GX_JS_SJCZQX3080"
},
"name": "RewritePath"
}
],
"id": "02024012311262643900000101579677",
"uri": "lb://myapi",
"order": 0
}
定义路由缓存策略
接口定义
/**
* 路由断言缓存实现
* 通过ServerWebExchange快速查找Route
* @author changxy
*/
public interface RoutePredicateCacheable {
/**
* 更新缓存路由
* @param routeDefinition
*/
void update(List<RouteDefinition> routeDefinition);
/**
* 根据请求上下文匹配对应路由
* @param exchange
* @return
*/
Optional<Route> getRoute(ServerWebExchange exchange);
static RoutePredicateCacheable empty() {
return new BlankRoutePredicateCacheable();
}
}
使用本地内存存放路由缓存
/**
* 本地内存Route对象缓存器
* RouteDefinitionRouteLocator类中处理RouteDefinition到Route的转换
* @author changxy
*/
public class InMemoryRoutePredicateCacheable implements RoutePredicateCacheable {
private final RouteDefinitionRouteLocator routeLocator;
private final Map<String, Route> routes = new ConcurrentHashMap<>(1024);
protected final static String CACHE_KEY_FORMAT = "%s:%s";
public InMemoryRoutePredicateCacheable(RouteDefinitionRouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Override
public void update(List<RouteDefinition> routeDefinitions) {
if (CollectionUtils.isEmpty(routeDefinitions)) {
return ;
}
// 清空缓存
routes.clear();
Map<String, Route> routeMap = this.routeLocator
.getRoutes()
.toStream()
.collect(Collectors.toMap(Route::getId, r -> r));
for (RouteDefinition routeDefinition : routeDefinitions) {
routes.put(key(routeDefinition), routeMap.get(routeDefinition.getId()));
}
System.out.println(1);
}
@Override
public Optional<Route> getRoute(ServerWebExchange exchange) {
return Optional.ofNullable(routes.get(key(exchange)));
}
public Optional<Route> lookupRoute(String routeId) {
return this.routeLocator
.getRoutes()
.toStream()
.filter(route -> Objects.equals(route.getId(), routeId))
.findFirst();
}
/**
* 根据路由定义生成key
* @param routeDefinition
* @return
*/
protected String key(RouteDefinition routeDefinition) {
Map<String, String> routeDefinitionParams = routeDefinition.getPredicates()
.stream()
.collect(
Collectors.toMap(
PredicateDefinition::getName,
p -> p.getArgs().get("_genkey_0"),
(k1, k2) -> k2
)
);
if (null != routeDefinitionParams
&& routeDefinitionParams.containsKey("Method")
&& routeDefinitionParams.containsKey("Path")) {
return String.format(CACHE_KEY_FORMAT, routeDefinitionParams.get("Method"), routeDefinitionParams.get("Path"));
}
return StringUtils.EMPTY;
}
/**
* 根据请求对象生成key
* @param exchange
* @return
*/
protected String key(ServerWebExchange exchange) {
String method = exchange.getRequest().getMethodValue();
String paths = exchange.getRequest().getPath().value();
return String.format(CACHE_KEY_FORMAT, method, paths);
}
}
我们的路由规则存放在Nacos配置中心,网关服务启动时、Nacos配置发生变更时,同步刷新路由缓存,这块可以根据实际情况定义缓存更新策略,部分伪代码如下:
List<RouteDefinition> routeDefinitions = list.stream().map(DynamicRoutingConfig.this::assembleRouteDefinition).collect(Collectors.toList());
// 20240124 更新Route缓存,优化路由匹配速度
routePredicateCacheable.update(routeDefinitions);
重写RoutePredicateHandlerMapping
public class CachingRoutePredicateHandlerMapping extends RoutePredicateHandlerMapping {
private final RoutePredicateCacheable routePredicateCacheable;
public CachingRoutePredicateHandlerMapping(FilteringWebHandler webHandler, RouteLocator routeLocator, GlobalCorsProperties globalCorsProperties, Environment environment, RoutePredicateCacheable routePredicateCacheable) {
super(webHandler, routeLocator, globalCorsProperties, environment);
this.routePredicateCacheable = routePredicateCacheable;
}
@Override
protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
Optional<Route> route = routePredicateCacheable.getRoute(exchange);
if (route.isPresent()) {
return Mono.just(route.get());
} else {
return super.lookupRoute(exchange);
}
}
}
定义AutoConfiguration
@Configuration
@ConditionalOnProperty(name = "route.cache.enabled", matchIfMissing = false)
@AutoConfigureBefore(GatewayAutoConfiguration.class)
public class FastRoutePredicateHandlerAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public RoutePredicateCacheable routePredicateCacheable(RouteDefinitionRouteLocator routeLocator) {
return new InMemoryRoutePredicateCacheable(routeLocator);
}
@Bean("cachingRoutePredicateHandlerMapping")
public RoutePredicateHandlerMapping routePredicateHandlerMapping(
FilteringWebHandler webHandler, RouteLocator routeLocator,
GlobalCorsProperties globalCorsProperties, Environment environment, RoutePredicateCacheable routePredicateCacheable) {
return new CachingRoutePredicateHandlerMapping(webHandler, routeLocator,
globalCorsProperties, environment, routePredicateCacheable);
}
}
不加载SpringCloudGateway自己的RoutePredicateHandlerMapping
@Configuration
@ConditionalOnProperty(name = "route.cache.enabled", matchIfMissing = false)
public class RoutePredicateBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
registry.removeBeanDefinition("routePredicateHandlerMapping");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}
优化效果测试
毫秒级响应了

重写SpringCloudGateway路由查找算法,性能提升100倍!的更多相关文章
- 优化临时表使用,SQL语句性能提升100倍
[问题现象] 线上mysql数据库爆出一个慢查询,DBA观察发现,查询时服务器IO飙升,IO占用率达到100%, 执行时间长达7s左右.SQL语句如下:SELECT DISTINCT g.*, cp. ...
- 转--优化临时表使用,SQL语句性能提升100倍
转自:http://www.51testing.com/html/01/n-867201-2.html [问题现象] 线上mysql数据库爆出一个慢查询,DBA观察发现,查询时服务器IO飙升,IO占用 ...
- Web 应用性能提升 10 倍的 10 个建议
转载自http://blog.jobbole.com/94962/ 提升 Web 应用的性能变得越来越重要.线上经济活动的份额持续增长,当前发达世界中 5 % 的经济发生在互联网上(查看下面资源的统计 ...
- MySQL 5.7 优化SQL提升100倍执行效率的深度思考(GO)
系统环境:微软云Linux DS12系列.Centos6.5 .MySQL 5.7.10.生产环境,step1,step2是案例,精彩的剖析部分在step3,step4. 1.慢sql语句大概需要13 ...
- 重构、插件化、性能提升 20 倍,Apache DolphinScheduler 2.0 alpha 发布亮点太多!
点击上方 蓝字关注我们 社区的小伙伴们,好消息!经过 100 多位社区贡献者近 10 个月的共同努力,我们很高兴地宣布 Apache DolphinScheduler 2.0 alpha 发布.这是 ...
- 阿里云maven仓库地址,速度提升100倍
参照:https://www.cnblogs.com/xxt19970908/p/6685777.html maven仓库用过的人都知道,国内有多么的悲催.还好有比较好用的镜像可以使用,尽快记录下来. ...
- 性能提升 40 倍!我们用 Rust 重写了自己的项目
前言 Rust 已经悄然成为了最受欢迎的编程语言之一.作为一门新兴底层系统语言,Rust 拥有着内存安全性机制.接近于 C/C++ 语言的性能优势.出色的开发者社区和体验出色的文档.工具链和IDE 等 ...
- 如何利用缓存机制实现JAVA类反射性能提升30倍
一次性能提高30倍的JAVA类反射性能优化实践 文章来源:宜信技术学院 & 宜信支付结算团队技术分享第4期-支付结算部支付研发团队高级工程师陶红<JAVA类反射技术&优化> ...
- 查询性能提升3倍!Apache Hudi 查询优化了解下?
从 Hudi 0.10.0版本开始,我们很高兴推出在数据库领域中称为 Z-Order 和 Hilbert 空间填充曲线的高级数据布局优化技术的支持. 1. 背景 Amazon EMR 团队最近发表了一 ...
- Elasticsearch Reindex性能提升10倍+实战
文章转载自: https://mp.weixin.qq.com/s?__biz=MzI2NDY1MTA3OQ==&mid=2247484134&idx=1&sn=750249a ...
随机推荐
- 文心一言 VS 讯飞星火 VS chatgpt (171)-- 算法导论13.2 4题
四.用go语言,证明:任何一棵含n个结点的二叉搜索树可以通过 O(n)次旋转,转变为其他任何一棵含n个结点的二叉搜索树.(提示:先证明至多n-1次右旋足以将树转变为一条右侧伸展的链.) 文心一言: 这 ...
- electron入门之配置镜像加速(四)
electron入门到入土,配置阿里镜像加速.为了防止后面我们打包龟速,需要给electron配置阿里镜像加速 在下面的文件内添加阿里镜像加速,你的文件位置不一定是这个 C:\Program File ...
- 微信小程序中的数组有许多常用的方法和用法
声明和初始化一个数组: var array = []; // 声明一个空数组 var array = [1, 2, 3]; // 声明并初始化一个有元素的数组 获取数组长度: var length = ...
- 十分钟从入门到精通(上)——OBS权限配置
[摘要]作为公有云的数据底座,大量的应用场景产生的数据都会存储到OBS对象存储服务中,如直播.电商.大数据可视化.机器学习.物联网等.作为公有云的海量存储基础服务, OBS提供了灵活的权限配置功能,解 ...
- 论文复现丨基于ModelArts实现Text2SQL
摘要:该论文提出了一种基于预训练 BERT 的新神经网络架构,称为 M-SQL.基于列的值提取分为值提取和值列匹配两个模块. 本文分享自华为云社区<基于ModelArts实现Text2SQL&g ...
- HTML 首页 欢迎页
HTML 首页 欢迎页,将下面代码复制出来,贴到HTML中,直接运行 <!DOCTYPE html> <html lang="en"> <head&g ...
- Dom4j 保存XML HL7-V3
dom4j selectNodes 取不到值 因为XML带有命名空间 HL7 Dom4j 保存XML String xmlPath = "D:\\BS004.xml"; Strin ...
- deepin15.11系统使用罗技k380键盘
罗技k380键盘官方支持安卓.windows.macos,就是没有支持Linux系统.在开发过程中使用的是Deepin15.11系统,如何连接罗技k380就是一个问题,折腾了一段时间后解决这个问题.记 ...
- PS 新建作业DUMP DBSQL_DUPLICATE_KEY_ERROR
1.CJ20N新建作业 在CJ20N中新建作业后,保存DUMP,报以下错误 2.相关NOTE 605584 - CN22: update termination when creating activ ...
- OKR之剑·实战篇04:OKR执行过程优化的那些关键事
作者:vivo 互联网平台产品研发团队 本文是<OKR 之剑>系列之实战第 4 篇--OKR执行过程不是一成不变的,团队和个人在执行中不断优化执行的具体行动,保障OKR的高效执行. 前言 ...