深入理解API网关以及SpringCloud Gateway的应用

最近的项目对接中接触到API网关的相关内容,也以此为契机梳理下我所理解的API网关以及SpringCloud Gateway的相关内容。

什么是API网关

    一个API网关的基本功能包含了统一接入、协议适配、流量管理与容错、以及安全防护,这四大基本功能构成了网关的核心功能。网关首要的功能是负责统一接入,然后将请求的协议转换成内部的接口协议,在调用的过程中还要有限流、降级、熔断等容错的方式来保护网关的整体稳定,同时网关还要做到基本的安全防护(防刷控制),以及黑白名单(比如IP白名单)等基本安全措施

除了基本的四大功能,网关运行良好的环境还包括注册中心(比如:ZK读取已发布的API接口的动态配置)。为了实现高性能,将数据全部异构到缓存(如:Redis)中,同时还可以配合本地缓存来进一步提高网关系统的性能。为了提高网关的吞吐率,可以使用NIO+Servlet 3 异步的方式,还可以利用Servlet 3 的异步特性将请求线程与业务线程分开,为后续的线程池隔离做好基本的支撑。访问日志的存储我们可以放到Hbase中,如果要作为开放网关使用,那么需要一个支持OAuth2.0的授权中心。还可以引入Nginx + lua的方式将一些基本的校验判断放到应用系统之上,这样可以更轻量化的处理接入的问题

API网关有什么用 

API网关应具有负载均衡,路由选择,流量控制,统一鉴权,熔断降级,失败重试,发布测试,缓存数据,日志记录等功能。

性能:API高可用,负载均衡,容错机制。
安全:权限身份认证、脱敏,流量清洗,后端签名(保证全链路可信调用),黑名单(非法调用的限制)。
日志:日志记录(spainid,traceid)一旦涉及分布式,全链路跟踪必不可少。
缓存:数据缓存。
监控:记录请求响应数据,api耗时分析,性能监控。
限流:流量控制,错峰流控,可以定义多种限流规则。
灰度:线上灰度部署,可以减小风险。
路由:动态路由规则。

API网关有哪些解决方案

比较流行的网关有:Nginx 、 Kong 、Orange等等,还有微服务网关Zuul 、Spring Cloud Gateway等等

Spring Cloud Gateway的特性

基于Spring Framework 5、Project Reactor和Spring Boot 2.0构建 Built on Spring Framework 5, Project Reactor and Spring Boot 2.0

能够在任意请求属性上匹配路由 Able to match routes on any request attribute.

predicates(谓词) 和 filters(过滤器)是特定于路由的 Predicates and filters are specific to routes.

集成了Hystrix断路器 Hystrix Circuit Breaker integration.

集成了Spring Cloud DiscoveryClient , Spring Cloud DiscoveryClient integration

易于编写谓词和过滤器 , Easy to write Predicates and Filters

请求速率限制 , Request Rate Limiting

路径重写 , Path Rewriting

使用SpringCloud Gateway实现路由转发

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-web</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

配置规则

    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p
                        .path("/usertest")
                        .filters(f -> f.addRequestHeader("router", "forward"))
                        .uri("http://localhost:18081"))
                .build();
    }

后续篇章继续介绍SpringCloud Gateway在熔断,限流,降级,鉴权等功能方面的应用

发布了117 篇原创文章 · 获赞 17 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Jack__iT/article/details/102942977
今日推荐