SpringCloud Gateway 路由转发性能优化

通过对SpringCloud Gateway的源码修改,例如缓存路由查找结果,避免了在大量路由时的性能瓶颈。改造包括启动类排除自动装配,继承并定制GatewayAutoConfiguration和RoutePredicateHandlerMapping。测试结果显示,优化后路由转发性能显著提升,特别是在路由表规模增大时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对源码做简单修改,比如,Path 匹配 /mock/** 则对路由查找结果进行缓存(注意这里缓存策略和方式仅仅是举例,根据实际需求情况来做)

public static final String MOCK_PATCH = "/mock/**";private Map<String, Route> hashCache = new ConcurrentHashMap<>(1024);protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
    String path = exchange.getRequest().getPath().subPath(0).value();  //符合Path规则,优先从缓存Map获取,时间复杂度近似于O(1)  if (pathMatcher.match(MOCK_PATCH, path)) {
      return Mono.justOrEmpty(hashCache.get(path))               .switchIfEmpty(getRouteMono(exchange, path));  }  return getRouteMono(exchange, path);}private Mono<Route> getRouteMono(ServerWebExchange exchange, String path) {
    return this.routeLocator.getRoutes()      //... 略过      .map(route -> {
          if (logger.isDebugEnabled()) {
            logger.debug("Route matched: " + route.getId());        }        validateRoute(route, exchange);        //符合Path规则,缓存路由        if (pathMatcher.match(MOCK_PATCH, path)) {
            hashCache.put(path, route);        }        return route;      });}

继续查阅源码,找到RoutePredicateHandlerMapping 是如何装配的。在GatewayAutoConfiguration 中实现了 SpringCloud Gateway 内部组件的自动装配,RoutePredicateHandlerMapping 也在其中,代码入下:

@Beanpublic RoutePredicateHandlerMapping routePredicateHandlerMapping(FilteringWebHandler webHandler,    RouteLocator routeLocator, GlobalCorsProperties globalCorsProperties, Environment environment) {
    return new RoutePredicateHandlerMapping(webHandler, routeLocator, globalCorsProperties, environment);}

很遗憾,官方没有给这个自动装配添加条件,我们无法自行装配替代默认装配。

我们只能采取以下步骤:

  1. 在 Springboot 启动类上增加排除 GatewayAutoConfiguration 的自动装配配置;

  2. 继承 GatewayAutoConfiguration 并完全拷贝其装配条件;

  3. 覆盖父类 routePredicateHandlerMapping方法,给装配添加条件;

  4. 继承RoutePredicateHandlerMapping ,覆盖其 lookupRoute方法,符合一定条件的请求,优先从缓存中查找路由。

改造 Gateway

修改启动类,排除自动装配

@SpringBootApplication(exclude = GatewayConfiguration.class)public class GatewayApplication {
    public static void main(String[] args) {
      SpringApplication.run(GatewayApplication.class, args);  }}

继承 GatewayAutoConfiguration

@Configuration(proxyBeanMethods = false)@ConditionalOnProperty(name = "spring.cloud.gateway.enabled", matchIfMissing = true)@EnableConfigurationProperties@AutoConfigureBefore({HttpH
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值