RouterConfig.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.yaozhitech.spring5.config;
  2. import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
  3. import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
  4. import org.springframework.cloud.gateway.route.RouteLocator;
  5. import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import reactor.core.publisher.Mono;
  9. @Configuration
  10. public class RouterConfig {
  11. @Bean
  12. public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
  13. //@formatter:off
  14. return builder.routes()
  15. .route("path_route", r -> r.path("/city_list.do")
  16. .filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter()).setKeyResolver(urlPathKeyResolver())))
  17. .uri("https://api.bbztx.com"))
  18. .route("host_route", r -> r.host("*.myhost.org")
  19. .uri("http://httpbin.org"))
  20. .route("rewrite_route", r -> r.path("/city_list")
  21. .filters(f -> f.rewritePath("city_list", // rewritePath方法会使用内建的过滤器重写路径
  22. "city_list.do"))
  23. .uri("https://api.bbztx.com"))
  24. .route("hystrix_fallback_route", r -> r.path("/slow_query.do")
  25. .filters(f -> f
  26. .rewritePath("_query.do", "")
  27. .hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback"))
  28. )
  29. .uri("http://127.0.0.1:8080"))
  30. // .route("hystrix_route", r -> r.host("*.hystrix.org")
  31. // .filters(f -> f.hystrix(c -> c.setName("slowcmd")))
  32. // .uri("http://httpbin.org"))
  33. // .route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
  34. // .filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
  35. // .uri("http://httpbin.org"))
  36. // .route("websocket_route", r -> r.path("/echo")
  37. // .uri("ws://localhost:9000"))
  38. .build();
  39. //@formatter:on
  40. }
  41. @Bean
  42. RedisRateLimiter redisRateLimiter() {
  43. return new RedisRateLimiter(1, 1);
  44. }
  45. // 用户限流
  46. KeyResolver userKeyResolver() {
  47. return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
  48. }
  49. // url限流
  50. KeyResolver urlPathKeyResolver() {
  51. return exchange -> Mono.just(exchange.getRequest().getPath().toString());
  52. }
  53. // ip限流
  54. KeyResolver ipKeyResolver() {
  55. return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostString());
  56. }
  57. }