SpringCloud Gateway笔记整理
2025/1/31 12:25:36
来源:https://blog.csdn.net/yichengjie_c/article/details/142317354
浏览:
次
关键词:SpringCloud Gateway笔记整理
- actuator配置, 访问http://localhost:9999/actuator/gateway/routes查看路由信息
management.endpoint.gateway.enabled=true
management.endpoints.web.exposure.include=gateway
- logger配置
logging.level.org.springframework.cloud.gateway=trace
logging.level.org.springframework.http.server.reactive=debug
logging.level.org.springframework.web.reactive=debug
logging.level.reactor.ipc.netty=debug
- 路由配置
# 访问http://localhost:9999/jd时,会转发到https://www.jd.com/
spring.cloud.gateway.routes[0].id=jd_route
spring.cloud.gateway.routes[0].uri=https://www.jd.com/
spring.cloud.gateway.routes[0].predicates[0]=Path=/jd
自定义GatewayFilter
- 实现GatewayFilter接口
@Component
public class CustomGatewayFilterFactoryextends AbstractNameValueGatewayFilterFactory implements Ordered {private static final String COUNT_START_TIME = "count_start_time" ;@Overridepublic GatewayFilter apply(NameValueConfig config) {return (exchange, chain) -> {exchange.getAttributes().put(COUNT_START_TIME, System.currentTimeMillis()) ;return chain.filter(exchange).then(Mono.fromRunnable(() ->{Long startTime = exchange.getAttribute(COUNT_START_TIME);if (startTime != null){long endTime = System.currentTimeMillis() - startTime ;log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");}}));};}@Overridepublic int getOrder() {return Ordered.LOWEST_PRECEDENCE ;}
}
- 配置过滤器
spring.cloud.gateway.routes[0].id=jd_route
spring.cloud.gateway.routes[0].uri=https://www.jd.com/
spring.cloud.gateway.routes[0].predicates[0]=Path=/jd
spring.cloud.gateway.routes[0].filters[0]=Custom=name,test
自定义GlobalFilter
- 实现GlobalFilter接口
@Component
public class AuthSignatureFilter implements GlobalFilter, Ordered {@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {String token = exchange.getRequest().getQueryParams().getFirst("token");if (StringUtils.isBlank(token)){exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);return exchange.getResponse().setComplete();}return chain.filter(exchange);}@Overridepublic int getOrder() {return -400;}
}
- 访问:http://localhost:9999/jd?token=123正常跳转到https://www.jd.com/
其他
- 执行流程
HttpWebHandlerAdapter
DispatcherHandler
RoutePredicateHandlerMapping
FilteringWebHandler
- 内置10个global 过滤器
RemoveCachedBodyFilter
AdaptCachedBodyGlobalFilter
NettyWriteResponseFilter
ForwardPathFilter
RouteToRequestUrlFilter
ReactiveLoadBalancerClientFilter
LoadBalancerServiceInstanceCookieFilter
WebsocketRoutingFilter
NettyRoutingFilter
ForwardRoutingFilter