由于版本迭代,有的时候需要做老接口的兼容适配,有很多种方式,比如在nginx配置路由规则,在网关配置路由规则,本篇通过使用反射的方式在网关层全局过滤器中重写request请求的方式实现url适配。
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* URL适配过滤器
*/
@Log4j2
@Component
public class AdapterURLFilter implements GlobalFilter, Ordered {
/**
* 路由转换:k-旧URL,v-新URL
*/
private static final Map<String, String> adapterURLMap;
static {
adapterURLMap = new ConcurrentHashMap<>();
adapterURLMap.put("oldUrlPath", "newUrlPath");
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
URI uri = request.getURI();
log.info("request original url={}", uri.getPath());
String newPath = adapterURLMap.get(uri.getPath());
if (StringUtils.isNotBlank(newPath)) {
try {
Class<?> clazz = URI.class;
Field pathField = clazz.getDeclaredField("path");
pathField.setAccessible(true);
pathField.set(uri, newPath);
} catch (Exception e) {
log.error("@@AdapterURLFilter@@ error! oldPath={}, newPath={}", uri.getPath(),
adapterURLMap.get(uri.getPath()), e);
}
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}