依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-gateway-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
</dependency>
问题描述
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: auth-service
uri: lb://auth-service
predicates:
- Path=/auth/** **/
- id: user-service
uri: lb://user-service
predicates:
- Path=/user/** **/
- id: payment-service
uri: lb://payment-service
predicates:
- Path=/pay/** **/
default-filters:
# - SwaggerHeaderFilter
- StripPrefix=1
// StripPrefix设置为1时, knife4j 文档可以访问到,但是 路由匹配地址无法匹配了
解决思路
自定义过滤器,
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import java.net.URI;
import java.net.URISyntaxException;
/**
* @description:
* @author: Tong
* @create: 2024-03-31 21:18
*/
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
private static final String KNIFE4J_URI = "/v2/api-docs";
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
if (!StringUtils.endsWithIgnoreCase(path,KNIFE4J_URI )) {
return chain.filter(exchange);
}
// 如果是 访问 knife4j网关聚合接口,则清理掉前缀 ,否则直接放行
String basePath = path.substring(0, path.lastIndexOf(KNIFE4J_URI));
String originalUrl = request.getURI().toString();
URI updatedUrl = URI.create(originalUrl.replace(basePath,""));
ServerHttpRequest newRequest = request.mutate().uri(updatedUrl).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
return chain.filter(newExchange);
};
}
}
配置改为
default-filters:
- SwaggerHeaderFilter
# - StripPrefix=1