springcloudgateway⾃定义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.tFallbackUri("forward:/fallback");
hystrixConfig.tName("openApiFallback");
RequestRateLimiterGatewayFilterFactory.Config config = new RequestRateLimiterGatewayFilterFactory.Config();
config.tRateLimiter(openApiRedisRateLimiter()).tKeyResolver(hostAddrKeyResolver());
utes()
.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.Request().getRemoteAddress().getHostName());
}
效果与yml中类似
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
死心塌地爱着你'[/**]':
allowedOrigins: "*"
expodHeaders:
- 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.burstCapacity: 200
其中RedisRateLimiter中的参数分别与plenishRate、redis-rate-limiter.burstCapacity相同。
初中一年级
⽽RequestRateLimiterGatewayFilterFactory与HystrixGatewayFilterFactory都是springcloud gateway内置的filter。还有更多内置Filter请看下图。
许多Filter源码看起来并不是很困难,⽤到可以多了解了解。
gateway源码相关也可以在了解学习。多了解了解可以解决很多问题。