继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【九月打卡】第15天 解读 SpringCloud Gateway Filter

两只角的蜗牛
关注TA
已关注
手记 25
粉丝 2
获赞 4

课程名称:Spring Cloud / Alibaba 微服务架构实战

课程章节:第7章-解读 SpringCloud Gateway Filter

课程讲师:张勤一

课程内容:

1. SpringCloud Gateway Filter的相关概念

  • SpringCloud Gateway是基于过滤器实现的,有prepost两种方式的filter,分别处理前置逻辑和后置逻辑。

    过程:客户端的请求先经过 pre 类型的filter, 然后将请求转发到具体的业务服务, 收到业务服务的响应之后,再经过post类型的filter处理,最后返回响应给客户端。

  • Filter 一共有两大类型:全局过滤器和局部过滤器

2.SpringCloud Gateway Filter的执行流程

图片描述

  • 过滤器有优先级之分,order越大,优先级越低越晚被执行。
  • 全局过滤器所有的请求都会执行。
  • 局部过滤器只有配置了请求才会执行。

3. 过滤器源码

  • RouteToRequestUrlFilter关键源码
    • RouteToRequestUrlFilter是全局过滤器,默认过滤所有请求。
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取此过滤器之间的过滤器
		Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        //如果为空,则直接放行
		if (route == null) {
			return chain.filter(exchange);
		}
		log.trace("RouteToRequestUrlFilter start");
		URI uri = exchange.getRequest().getURI();
		boolean encoded = containsEncodedParts(uri);
		URI routeUri = route.getUri();

		if (hasAnotherScheme(routeUri)) {
			// this is a special url, save scheme to special attribute
			// replace routeUri with schemeSpecificPart
			exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR,
					routeUri.getScheme());
			routeUri = URI.create(routeUri.getSchemeSpecificPart());
		}

		if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) {
			// Load balanced URIs should always have a host. If the host is null it is
			// most
			// likely because the host name was invalid (for example included an
			// underscore)
			throw new IllegalStateException("Invalid host: " + routeUri.toString());
		}
		//将微服务路径转换为真实的请求路径
		URI mergedUrl = UriComponentsBuilder.fromUri(uri)
				// .uri(routeUri)
				.scheme(routeUri.getScheme()).host(routeUri.getHost())
				.port(routeUri.getPort()).build(encoded).toUri();
		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl);
		return chain.filter(exchange);
	}

课程截图:

img
img

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP