API 网关

API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题:

  1. 客户端会多次请求不同的微服务,增加了客户端的复杂性。
  2. 存在跨域请求,在一定场景下处理相对复杂。
  3. 认证复杂,每个服务都需要独立认证。
  4. 难以重构,随着项目的迭代,可能需要重新划分微服务。例如,可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信,那么重构将会很难实施。
  5. 某些微服务可能使用了防火墙 / 浏览器不友好的协议,直接访问会有一定的困难。

以上这些问题可以借助 API 网关解决。API 网关是介于客户端和服务器端之间的中间层,所有的外部请求都会先经过 API 网关这一层。也就是说,API 的实现方面更多的考虑业务逻辑,而安全、性能、监控可以交由 API 网关来做,这样既提高业务灵活性又不缺安全性,典型的架构图如图所示:

使用 API 网关后的优点如下:

  • 易于监控。可以在网关收集监控数据并将其推送到外部系统进行分析。
  • 易于认证。可以在网关上进行认证,然后再将请求转发到后端的微服务,而无须在每个微服务中进行认证。
  • 减少了客户端与各个微服务之间的交互次数。

API 网关选型

业界的情况:

我前面的文章<Netflix网关zuul(1.x和2.x)全解析>已经介绍了zuul1 和zuul2,现在就尝试从实例入手介绍一下spring cloud gateway

首先我们一步步实现一个最简单的网关例子

步骤1:在http://start.spring.io网站上创建一个spring-cloud-gateway-example项目,依赖spring-cloud-gateway,如下图所示

此时生产了一个spring-cloud-gateway-example的空项目包,pom.xml文件如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.3.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>spring-cloud-gateway-example</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>spring-cloud-gateway-example</name>
  15. <description>Demo project for Spring Boot</description>
  16.  
  17. <properties>
  18. <java.version>1.8</java.version>
  19. <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
  20. </properties>
  21.  
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.springframework.cloud</groupId>
  25. <artifactId>spring-cloud-starter-gateway</artifactId>
  26. </dependency>
  27.  
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-test</artifactId>
  31. <scope>test</scope>
  32. </dependency>
  33. </dependencies>
  34.  
  35. <dependencyManagement>
  36. <dependencies>
  37. <dependency>
  38. <groupId>org.springframework.cloud</groupId>
  39. <artifactId>spring-cloud-dependencies</artifactId>
  40. <version>${spring-cloud.version}</version>
  41. <type>pom</type>
  42. <scope>import</scope>
  43. </dependency>
  44. </dependencies>
  45. </dependencyManagement>
  46.  
  47. <build>
  48. <plugins>
  49. <plugin>
  50. <groupId>org.springframework.boot</groupId>
  51. <artifactId>spring-boot-maven-plugin</artifactId>
  52. </plugin>
  53. </plugins>
  54. </build>
  55.  
  56. <repositories>
  57. <repository>
  58. <id>spring-milestones</id>
  59. <name>Spring Milestones</name>
  60. <url>https://repo.spring.io/milestone</url>
  61. </repository>
  62. </repositories>
  63.  
  64. </project>

2.创建一个Route实例的配置类GatewayRoutes

  1. package com.example.springcloudgatewayexample;
  2.  
  3. import org.springframework.cloud.gateway.route.RouteLocator;
  4. import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. @Configuration
  8. public class GatewayRoutes {
  9. @Bean
  10. public RouteLocator routeLocator(RouteLocatorBuilder builder) {
  11. return builder.routes()
  12. .route(r ->
  13. r.path("/java/**")
  14. .filters(
  15. f -> f.stripPrefix(1)
  16. )
  17. .uri("http://localhost:8090/helloWorld")
  18. )
  19. .build();
  20. }
  21. }

当然,也可以不适用配置类,使用配置文件,如下图所示

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - predicates:
  6. - Path=/java/**
  7. filters:
  8. - StripPrefix=1
  9. uri: "http://localhost:8090/helloWorld"

不过,为了调试方便,我们使用配置类方式。

此时项目已经完成,足够简单吧。

3.启动此项目

>>因api网关需要转发到一个服务上,本文为http://localhost:8090/helloWorld,那需要先启动我上文<spring boot整合spring5-webflux从0开始的实战及源码解析>,你也可以创建一个普通的web项目,启动端口设置为8090,然后启动。

  1. . ____ _ __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  5. ' |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot :: (v2.1.3.RELEASE)
  8.  
  9. 2019-02-21 09:29:07.450 INFO 11704 --- [ main] c.e.demo.Spring5WebfluxApplication : Starting Spring5WebfluxApplication on DESKTOP-405G2C8 with PID 11704 (E:\workspaceForCloud\spring5-webflux\target\classes started by dell in E:\workspaceForCloud\spring5-webflux)
  10. 2019-02-21 09:29:07.455 INFO 11704 --- [ main] c.e.demo.Spring5WebfluxApplication : No active profile set, falling back to default profiles: default
  11. 2019-02-21 09:29:09.409 INFO 11704 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8090
  12. 2019-02-21 09:29:09.413 INFO 11704 --- [ main] c.e.demo.Spring5WebfluxApplication : Started Spring5WebfluxApplication in 2.304 seconds (JVM running for 7.311)

>>以spring boot方式启动spring-cloud-gateway-example项目,日志如下

  1. 2019-02-21 10:34:33.435 INFO 8580 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$1e059320] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  2.  
  3. . ____ _ __ _ _
  4. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  5. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  6. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  7. ' |____| .__|_| |_|_| |_\__, | / / / /
  8. =========|_|==============|___/=/_/_/_/
  9. :: Spring Boot :: (v2.1.3.RELEASE)
  10.  
  11. 2019-02-21 10:34:33.767 INFO 8580 --- [ main] e.s.SpringCloudGatewayExampleApplication : No active profile set, falling back to default profiles: default
  12. 2019-02-21 10:34:34.219 INFO 8580 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=d98183ec-3e46-38ba-ba4c-e976a1017dce
  13. 2019-02-21 10:34:34.243 INFO 8580 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$1e059320] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  14. 2019-02-21 10:34:44.367 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [After]
  15. 2019-02-21 10:34:44.367 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Before]
  16. 2019-02-21 10:34:44.367 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Between]
  17. 2019-02-21 10:34:44.367 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Cookie]
  18. 2019-02-21 10:34:44.367 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Header]
  19. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Host]
  20. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Method]
  21. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Path]
  22. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Query]
  23. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [ReadBodyPredicateFactory]
  24. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [RemoteAddr]
  25. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [Weight]
  26. 2019-02-21 10:34:44.368 INFO 8580 --- [ main] o.s.c.g.r.RouteDefinitionRouteLocator : Loaded RoutePredicateFactory [CloudFoundryRouteService]
  27. 2019-02-21 10:34:44.920 INFO 8580 --- [ main] o.s.b.web.embedded.netty.NettyWebServer : Netty started on port(s): 8080
  28. 2019-02-21 10:34:44.923 INFO 8580 --- [ main] e.s.SpringCloudGatewayExampleApplication : Started SpringCloudGatewayExampleApplication in 12.329 seconds (JVM running for 13.126)

4.测试,浏览器访问http://localhost:8080/java/helloWorld

返回hello world !

5.从上面的代码和配置及实例中,我们可以看出spring cloud gateway处理request请求的流程如下所示:

即在最前端,启动一个netty server(默认端口为8080)接受请求,然后通过Routes(每个Route由Predicate(等同于HandlerMapping)和Filter(等同于HandlerAdapter))处理后通过Netty Client发给响应的微服务。

那么在gateway本身最重要的应该是Route(Netty Server和Client已经封装好了),它由RouteLocatorBuilder构建,内部包含Predicate和Filter,

  1. private Route(String id, URI uri, int order, AsyncPredicate<ServerWebExchange> predicate, List<GatewayFilter> gatewayFilters) {
  2. this.id = id;
  3. this.uri = uri;
  4. this.order = order;
  5. this.predicate = predicate;
  6. this.gatewayFilters = gatewayFilters;
  7. }

那么我们就来探讨一下这两个组件吧

5.1.Predicate

Predicte由PredicateSpec来构建,主要实现有:

以path为例

  1. /**
  2. * A predicate that checks if the path of the request matches the given pattern
  3. * @param patterns the pattern to check the path against.
  4. * The pattern is a {@link org.springframework.util.PathMatcher} pattern
  5. * @return a {@link BooleanSpec} to be used to add logical operators
  6. */
  7. public BooleanSpec path(String... patterns) {
  8. return asyncPredicate(getBean(PathRoutePredicateFactory.class)
  9. .applyAsync(c -> c.setPatterns(Arrays.asList(patterns))));
  10. }

PathRoutePredicateFactory中执行

  1. @Override
  2. public Predicate<ServerWebExchange> apply(Config config) {
  3. final ArrayList<PathPattern> pathPatterns = new ArrayList<>();
  4. synchronized (this.pathPatternParser) {
  5. pathPatternParser.setMatchOptionalTrailingSeparator(
  6. config.isMatchOptionalTrailingSeparator());
  7. config.getPatterns().forEach(pattern -> {
  8. PathPattern pathPattern = this.pathPatternParser.parse(pattern);
  9. pathPatterns.add(pathPattern);
  10. });
  11. }
  12. return exchange -> {
  13. PathContainer path = parsePath(exchange.getRequest().getURI().getPath());
  14.  
  15. Optional<PathPattern> optionalPathPattern = pathPatterns.stream()
  16. .filter(pattern -> pattern.matches(path)).findFirst();
  17.  
  18. if (optionalPathPattern.isPresent()) {
  19. PathPattern pathPattern = optionalPathPattern.get();
  20. traceMatch("Pattern", pathPattern.getPatternString(), path, true);
  21. PathMatchInfo pathMatchInfo = pathPattern.matchAndExtract(path);
  22. putUriTemplateVariables(exchange, pathMatchInfo.getUriVariables());
  23. return true;
  24. }
  25. else {
  26. traceMatch("Pattern", config.getPatterns(), path, false);
  27. return false;
  28. }
  29. };
  30. }

5.2.Filter

Filter分两种,一种GatewayFilter,一种GlobalFilter

5.2.1 GatewayFilter

GatewayFilter由GatewayFilterSpec构建,GatewayFilter的构建器

5.2.2 GlobalFilter

5.3 GlobalFilter和GatewayFilter的联系

FilteringWebHandler.GatewayFilterAdapter代理了GlobalFilter

6.总结

本文从一个spring-cloud-gateway实例入手,深入浅出的介绍了spring-cloud-gateway的组件,并从源码角度给出了实现的原理。

spring-cloud-gateway在最前端,启动一个netty server(默认端口为8080)接受请求,然后通过Routes(每个Route由Predicate(等同于HandlerMapping)和Filter(等同于HandlerAdapter))处理后通过Netty Client发给响应的微服务。

Predicate和Filter的各个实现定义了spring-cloud-gateway拥有的功能。

参考资料:

【1】https://www.infoq.cn/article/comparing-api-gateway-performances

【2】https://dzone.com/articles/spring-cloud-gateway-configuring-a-simple-route

从0开始构建你的api网关--Spring Cloud Gateway网关实战及原理解析的更多相关文章

  1. spring cloud:服务网关 Spring Cloud GateWay 入门

    Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使 ...

  2. Spring Cloud实战 | 第十一篇:Spring Cloud Gateway 网关实现对RESTful接口权限控制和按钮权限控制

    一. 前言 hi,大家好,这应该是农历年前的关于开源项目 的最后一篇文章了. 有来商城 是基于 Spring Cloud OAuth2 + Spring Cloud Gateway + JWT实现的统 ...

  3. Spring Cloud gateway 网关服务二 断言、过滤器

    微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...

  4. .net core下,Ocelot网关与Spring Cloud Gateway网关的对比测试

    有感于 myzony 发布的 针对 Ocelot 网关的性能测试 ,并且公司下一步也需要对.net和java的应用做一定的整合,于是对Ocelot网关.Spring Cloud Gateway网关做个 ...

  5. Spring Cloud gateway 网关四 动态路由

    微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...

  6. Spring Cloud 微服务三: API网关Spring cloud gateway

    前言:前面介绍了一款API网关组件zuul,不过发现spring cloud自己开发了一个新网关gateway,貌似要取代zuul,spring官网上也已经没有zuul的组件了(虽然在仓库中可以更新到 ...

  7. API网关spring cloud gateway和负载均衡框架ribbon实战

    通常我们如果有一个服务,会部署到多台服务器上,这些微服务如果都暴露给客户,是非常难以管理的,我们系统需要有一个唯一的出口,API网关是一个服务,是系统的唯一出口.API网关封装了系统内部的微服务,为客 ...

  8. 微服务网关 Spring Cloud Gateway

    1.  为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...

  9. Spring Cloud gateway 网关服务 一

    之前我们介绍了 zuul网关服务,今天聊聊spring cloud gateway 作为spring cloud的亲儿子网关服务.很多的想法都是参照zuul,为了考虑zuul 迁移到gateway 提 ...

随机推荐

  1. 浅谈Java多线程的同步问题 【转】

    多线程的同步依靠的是对象锁机制,synchronized关键字的背后就是利用了封锁来实现对共享资源的互斥访问. 下面以一个简单的实例来进行对比分析.实例要完成的工作非常简单,就是创建10个线程,每个线 ...

  2. python while 循环语句

    Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务.其基本形式为: while 判断条件: 执行语句-- 执行语句可以是单个语句或语句 ...

  3. Flask入门之Jinjia模板的一些语法

    1. 变量表示 {{ argv }} 2. 赋值操作 {% set links = [ ('home',url_for('.home')), ('service',url_for('.service' ...

  4. JDK10都发布了,nio你了解多少?

    前言 只有光头才能变强 回顾前面: 给女朋友讲解什么是代理模式 包装模式就是这么简单啦 本来我预想是先来回顾一下传统的IO模式的,将传统的IO模式的相关类理清楚(因为IO的类很多). 但是,发现在整理 ...

  5. .NET开发设计模式-模板模式

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  6. Python《学习手册:第一章-习题》

    人们选择Python的六大主要原因是什么? 软件质量:Python注重可读性.一致性和软件质量. Python代码的设计致力于可读性,因此具备了比传统脚本语言更优秀的可重用性和可维护性. Python ...

  7. Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务

    1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...

  8. posix,perl正则表达式区别

    1.正则表达式(Regular Expression,缩写为regexp,regex或regxp),又称正规表达式.正规表示式或常规表达式或正规化表示法或正规表示法,是指一个用来描述或者匹配一系列符合 ...

  9. XML解析的四种方法 建议使用demo4j解析 测试可以用

    https://www.cnblogs.com/longqingyang/p/5577937.html 4.DOM4J解析  特征: 1.JDOM的一种智能分支,它合并了许多超出基本XML文档表示的功 ...

  10. 关于maven的配置使用 这一篇还比较全 2017.12.13

    https://www.cnblogs.com/tangshengwei/p/6341462.html