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, UriConfiguration uriConfiguration) { String httpUri = uriConfiguration.getHttpbin(); //@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(httpUri)) .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(httpUri)) // .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("circuitbreaker_route", r -> r.path("/slow1_query.do") .filters(f -> f .rewritePath("_query.do", "") .circuitBreaker(c -> c.setName("slow").setFallbackUri("forward:/hystrixfallback")) ) .uri("http://127.0.0.1:8080")) // .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()); } }