为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java

课程名称: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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消