网关路由:
1.创建新模块
2.引入网关依赖
<!--网关--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!--nacos discovery--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--负载均衡--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
3.编写启动类
4.配置路由规则
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 192.168.88.95:8848
gateway:
routes:
- id: item-service
uri: lb://item-service
predicates:
- Path=/items/**,/search/**
5.查找路由断言、过滤器语法https://docs.spring.io/spring-cloud-gateway/reference/spring-cloud-gateway-server-mvc/gateway-request-predicates.html
网关请求处理流程:predicates=》filter=》微服务=》filter=》predicates=》客户端
1.由客户端发送给handlermapping:HandlerMapping默认实现是RoutePredicatesHandlerMapping实现的,根据其匹配到的路由存入上下文,并把请求传递给WebHandler
2.webHandler:默认实现FilteringWebHandler,会加载网关中配置的过滤器,放入集合并排序生成过滤器链再依次执行
3.在所有过滤器链的最后还有NettyRoutingFilter:将请求转发给微服务,再把微服务返回的信息依次返回存入上下文
自定义全局过滤器:
1.继承globalfilter后还需要确定执行顺序,因此我们再继承ordered,我们需要确保自己的过滤器在nettyroutingfilter之前执行(pre),因此需要让order小于他
2.filter中exchange表示过滤器内的上下文,chain表示下一个过滤器,因此放行之后我们要把执行链传给下一个过滤器
@Component public class MyGlobalFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); // 放行 return chain.filter(exchange); } @Override public int getOrder() { // 过滤器执行顺序,值越小,优先级越高 return 0; } }
标签:服务,exchange,spring,filter,过滤器,gateway,cloud From: https://www.cnblogs.com/kun1790051360/p/18153748