ApiRouteLocator.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.yiidata.dataops.server.config;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.cloud.netflix.zuul.filters.Route;
  4. import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
  5. import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
  6. import java.util.Random;
  7. /**
  8. * <pre>
  9. *
  10. * Created by zhenqin.
  11. * User: zhenqin
  12. * Date: 2022/4/25
  13. * Time: 下午7:12
  14. * Vendor: yiidata.com
  15. *
  16. * </pre>
  17. *
  18. * @author zhenqin
  19. */
  20. @Slf4j
  21. public class ApiRouteLocator extends SimpleRouteLocator {
  22. /**
  23. * zull 配置
  24. */
  25. final ZuulProperties properties;
  26. /**
  27. * 随机策略
  28. */
  29. final Random r = new Random();
  30. public ApiRouteLocator(String servletPath, ZuulProperties properties) {
  31. super(servletPath, properties);
  32. this.properties = properties;
  33. }
  34. @Override
  35. protected Route getRoute(ZuulProperties.ZuulRoute route, String path) {
  36. if (route == null) {
  37. return null;
  38. }
  39. if (log.isDebugEnabled()) {
  40. log.debug("route matched=" + route);
  41. }
  42. String targetPath = path;
  43. String prefix = this.properties.getPrefix();
  44. if (prefix.endsWith("/")) {
  45. prefix = prefix.substring(0, prefix.length() - 1);
  46. }
  47. if (path.startsWith(prefix + "/") && this.properties.isStripPrefix()) {
  48. targetPath = path.substring(prefix.length());
  49. }
  50. if (route.isStripPrefix()) {
  51. int index = route.getPath().indexOf("*") - 1;
  52. if (index > 0) {
  53. String routePrefix = route.getPath().substring(0, index);
  54. targetPath = targetPath.replaceFirst(routePrefix, "");
  55. prefix = prefix + routePrefix;
  56. }
  57. }
  58. Boolean retryable = this.properties.getRetryable();
  59. if (route.getRetryable() != null) {
  60. retryable = route.getRetryable();
  61. }
  62. // 如果包含逗号,说明有多个地址,需要负载均衡
  63. if(route.getLocation().contains(",")) {
  64. final String[] segs = route.getLocation().split(",");
  65. // 随机策略
  66. String loc = segs[r.nextInt(segs.length)];
  67. //log.info("loc->> " + loc);
  68. return new Route(route.getId(),
  69. targetPath,
  70. loc,
  71. prefix,
  72. retryable,
  73. route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null,
  74. route.isStripPrefix());
  75. }
  76. return new Route(route.getId(),
  77. targetPath,
  78. route.getLocation(),
  79. prefix,
  80. retryable,
  81. route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null,
  82. route.isStripPrefix());
  83. }
  84. }