123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package com.yaozhitech.spring5.config;
- import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
- import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
- import org.springframework.cloud.gateway.route.RouteLocator;
- import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import reactor.core.publisher.Mono;
- @Configuration
- public class RouterConfig {
- @Bean
- public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
- //@formatter:off
- return builder.routes()
- .route("path_route", r -> r.path("/city_list.do")
- .filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter()).setKeyResolver(urlPathKeyResolver())))
- .uri("https://api.bbztx.com"))
- .route("host_route", r -> r.host("*.myhost.org")
- .uri("http://httpbin.org"))
- .route("rewrite_route", r -> r.path("/city_list")
- .filters(f -> f.rewritePath("city_list", // rewritePath方法会使用内建的过滤器重写路径
- "city_list.do"))
- .uri("https://api.bbztx.com"))
- .route("hystrix_fallback_route", r -> r.path("/slow_query.do")
- .filters(f -> f
- .rewritePath("_query.do", "")
- .hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback"))
- )
- .uri("http://127.0.0.1:8080"))
- // .route("hystrix_route", r -> r.host("*.hystrix.org")
- // .filters(f -> f.hystrix(c -> c.setName("slowcmd")))
- // .uri("http://httpbin.org"))
- // .route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
- // .filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
- // .uri("http://httpbin.org"))
- // .route("websocket_route", r -> r.path("/echo")
- // .uri("ws://localhost:9000"))
- .build();
- //@formatter:on
- }
-
- @Bean
- RedisRateLimiter redisRateLimiter() {
- return new RedisRateLimiter(1, 1);
- }
-
- // 用户限流
- KeyResolver userKeyResolver() {
- return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
- }
-
- // url限流
- KeyResolver urlPathKeyResolver() {
- return exchange -> Mono.just(exchange.getRequest().getPath().toString());
- }
-
- // ip限流
- KeyResolver ipKeyResolver() {
- return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostString());
- }
- }
|