Spring Cloud Gateway网关下Knife4j文档聚合,以及动态路由的读取和代码配置
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Flux;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/api/test")
.uri("http://localhost:8081")
.order(1)
.filters(f -> f.addResponseHeader("X-Response-Default", "Default-Header-Value"))
.id("test_route")
)
.build();
}
@Bean
public PredicateDefinition customPredicate() {
PredicateDefinition predicate = new PredicateDefinition();
predicate.setName("Path");
predicate.addArg(Collections.singletonMap("pattern", "/api/**"));
return predicate;
}
@Bean
public FilterDefinition customFilter() {
FilterDefinition filter = new FilterDefinition();
filter.setName("AddResponseHeader");
filter.addArg(Collections.singletonMap("name", "X-Response-Custom"));
filter.addArg(Collections.singletonMap("value", "Custom-Header-Value"));
return filter;
}
}
这个配置类定义了一个自定义的路由定位器,它会将匹配 /api/test
路径的请求转发到 http://localhost:8081
,并添加了一个自定义的响应头。同时,它展示了如何定义一个路径匹配的断言和一个响应头的过滤器。这些定义可以用于动态路由和过滤的配置,在Spring Cloud Gateway中,它们可以和配置服务器结合,实现动态路由的管理。
评论已关闭