springcloud gateway自定义route代码配置内置Filter

本章简单介绍了如何使用java代码配置springcloud gateway的route,已及集成gateway内置的限流组件。

起因

因为有需求需要自定义route,完成自定义后route后发现不知道怎么添加内置的RequestRateLimiter限流组件,网上大多都是yml配置的。

解决办法

废话不多先直接上代码

@Bean
public RouteLocator routes(RouteLocatorBuilder builder, 
        RequestRateLimiterGatewayFilterFactory requestRateLimiterGatewayFilterFactory, 
        HystrixGatewayFilterFactory hystrixGatewayFilterFactory) {
    HystrixGatewayFilterFactory.Config hystrixConfig = new HystrixGatewayFilterFactory.Config();
    hystrixConfig.setFallbackUri("forward:/fallback");
    hystrixConfig.setName("openApiFallback");
    RequestRateLimiterGatewayFilterFactory.Config config = new RequestRateLimiterGatewayFilterFactory.Config();
    config.setRateLimiter(openApiRedisRateLimiter()).setKeyResolver(hostAddrKeyResolver());
    return builder.routes()
            .route("openApi", r -> r.path("/openApi")
                    .and()
                    .readBody(JSONObject.class, requestBody -> true)
                    .filters(f -> f.filter(new OpenApiFilter())
                    .filter(requestRateLimiterGatewayFilterFactory.apply(config))
                    .filter(hystrixGatewayFilterFactory.apply(hystrixConfig)))
                    .uri("lb://openApi"))
                    .build();
}

@Bean
public RedisRateLimiter openApiRedisRateLimiter() {
    return new RedisRateLimiter(1, 200);
}

/**
    * 用户ip限流
    * @return
    */
@Bean
public KeyResolver hostAddrKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}

效果与yml中类似

spring:
    cloud:
        gateway:
              globalcors:
                  corsConfigurations:
                    '[/**]':
                      allowedOrigins: "*"
                      exposedHeaders:
                      - content-type
                      allowedHeaders:
                      - content-type
                      allowCredentials: true
                      allowedMethods: "*"
              routes:
              - id: main
                uri: lb://main
                predicates:
                - Path=/main/**
                filters:
                - RemoveRequestHeader=from
                - StripPrefix=1
                - name: CustomRequestRateLimiter
                  args:
                    #用于限流的键的解析器的 Bean 对象的名字,使用 SpEL 表达式根据#{@beanName}获取Bean对象
                    key-resolver: '#{@hostAddrKeyResolver}'
                    #令牌桶填充速率
                    redis-rate-limiter.replenishRate: 1
                    #令牌桶总容量
                    redis-rate-limiter.burstCapacity: 200

其中RedisRateLimiter中的参数分别与redis-rate-limiter.replenishRate、redis-rate-limiter.burstCapacity相同。
而RequestRateLimiterGatewayFilterFactory与HystrixGatewayFilterFactory都是springcloud gateway内置的filter。还有更多内置Filter请看下图。
许多Filter源码看起来并不是很困难,用到可以多了解了解。
图片名称


gateway源码相关也可以在 芋道源码 了解学习。多了解了解可以解决很多问题。