前言
在公司构建一个项目,统一建一套网关,现将网关的功能和构建过程介绍如下。
网关功能
1、校验请求格式
2、验证参数签名权限,修改请求头信息
3、修改请求体,增加traceId(便于日志追踪)
构建过程
使用spring-cloud-gateway 3.0.3包,集成到spring-boot 2.5.2
1、校验请求格式
@Component
public class RequestFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L).collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
}
@Override
public int getOrder() {
return -1000; // 执行顺序,必须为负数,值越小执行顺序越靠前
}
}
2、验证参数签名权限,修改请求头信息
@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
private final AuthProperties authProperties;
private final ObjectMapper objectMapper;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
private RedisUtil redisUtil;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
if (FilterUtil.isSkip(path,authProperties,antPathMatcher)) {
return chain.filter(exchange);
}
ServerHttpRequest req = exchange.getRequest();
ServerHttpResponse res = exchange.getResponse();
版权声明:本文为swangooth原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。