12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package com.yiidata.dataops.server.config;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.cloud.netflix.zuul.filters.Route;
- import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
- import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
- import java.util.Random;
- /**
- * <pre>
- *
- * Created by zhenqin.
- * User: zhenqin
- * Date: 2022/4/25
- * Time: 下午7:12
- * Vendor: yiidata.com
- *
- * </pre>
- *
- * @author zhenqin
- */
- @Slf4j
- public class ApiRouteLocator extends SimpleRouteLocator {
- /**
- * zull 配置
- */
- final ZuulProperties properties;
- /**
- * 随机策略
- */
- final Random r = new Random();
- public ApiRouteLocator(String servletPath, ZuulProperties properties) {
- super(servletPath, properties);
- this.properties = properties;
- }
- @Override
- protected Route getRoute(ZuulProperties.ZuulRoute route, String path) {
- if (route == null) {
- return null;
- }
- if (log.isDebugEnabled()) {
- log.debug("route matched=" + route);
- }
- String targetPath = path;
- String prefix = this.properties.getPrefix();
- if (prefix.endsWith("/")) {
- prefix = prefix.substring(0, prefix.length() - 1);
- }
- if (path.startsWith(prefix + "/") && this.properties.isStripPrefix()) {
- targetPath = path.substring(prefix.length());
- }
- if (route.isStripPrefix()) {
- int index = route.getPath().indexOf("*") - 1;
- if (index > 0) {
- String routePrefix = route.getPath().substring(0, index);
- targetPath = targetPath.replaceFirst(routePrefix, "");
- prefix = prefix + routePrefix;
- }
- }
- Boolean retryable = this.properties.getRetryable();
- if (route.getRetryable() != null) {
- retryable = route.getRetryable();
- }
- // 如果包含逗号,说明有多个地址,需要负载均衡
- if(route.getLocation().contains(",")) {
- final String[] segs = route.getLocation().split(",");
- // 随机策略
- String loc = segs[r.nextInt(segs.length)];
- //log.info("loc->> " + loc);
- return new Route(route.getId(),
- targetPath,
- loc,
- prefix,
- retryable,
- route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null,
- route.isStripPrefix());
- }
- return new Route(route.getId(),
- targetPath,
- route.getLocation(),
- prefix,
- retryable,
- route.isCustomSensitiveHeaders() ? route.getSensitiveHeaders() : null,
- route.isStripPrefix());
- }
- }
|