spring cloud 2.x版本 Gateway路由网关教程

前言

本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3

本文基于前两篇文章 eureka-server、eureka-client、eureka-ribbon 和 eureka-feign 的实现。 参考

  • eureka-server[1]
  • eureka-client[2]
  • eureka-ribbon[3]
  • eureka-feign[4]

概念

Spring Cloud Gateway 是 Spring Cloud 的一个新项目,该项目是基于 Spring5.0,Sprint Boot2.0 和 Project Reactor 等技术开发的网关,它的目的是在微服务架构中提供一种简单有效的统一 api 路由管理方式。 Spring Cloud Gateway 目标是要替代 Netflix Zuul,其不仅提供统一的路由管理方式,还提供一套基于 Fliter 链的方式的网关其他功能,比如:限流、埋点、安全监控等。

名称术语

  • Route(路由):网关的基本模块,它有一个 id、一个目标 uri、一组断言和一组过滤器组成,如果断言为真,则路由匹配。
  • Predicate(断言):是一个 java8 的 Predicate。输入类型是一个 ServerWebExchange。可以使用它来匹配来自 HTTP 请求的内容。
  • Filter(过滤器):是 org.springframework.cloud.gateway.filter.GatewayFilter 的实例,可以使用它来修改请求和响应。

流程

spring cloud 2.x版本 Gateway路由网关教程_第1张图片

客户端向 Spring Cloud Gateway 发出请求。如果 Gateway Handler 映射确定请求与路由匹配,则将其发送到 Gateway Web Handler。Gateway Web Handler 通过特定于请求的筛选器链发送请求。筛选器由虚线分隔的原因是,筛选器可以在发送代理请求之前或之后执行逻辑。执行所有“pre”筛选逻辑,然后发出代理请求。在发出代理请求后,执行“POST”筛选逻辑。

创建 Zuul 工程

1.1 创建 sping boot 工程:spring-gateway

1.2 添加 pom.xml 相关依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webfluxartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>

1.3 application.yml 添加配置信息

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
        discovery:
          locator:
            enabled: true
eureka:
  instance:
    hostname: eureka1.server.com
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      defaultZone: http://eureka1.server.com:8701/eureka/,http://eureka2.server.com:8702/eureka/,http://eureka3.server.com:8703/eureka/

Spring.cloud.gateway.discovery.locator.enabled:true 这里先简单使用了默认的创建路由规则,自动根据 serviceid 创建路由的功能

1.4 启动类 SpringGatewayApplication 说明

前几片文章中都在对应的启动类中增加了@EnableEurekaClient 或@EnableDiscoveryClient 注解,今天看文档突然发现,不用加@Enable*注解也可以自动添加到注册中心,是因为在 Spring Cloud Edgware 版本之后,只要加上相关的依赖,并进行相应的配置就可以将服务自动注册到服务发现组件上。

1.5 启动相关服务

按顺序启动 eureka-server、eureka-client、eureka-ribbon、spring-gateway 服务。 打开浏览器,先去 eureka-server 服务中心看一下服务是否正常启动,如下如: spring cloud 2.x版本 Gateway路由网关教程_第2张图片 截图中红框代表所有服务已经正常启动。 然后新打来浏览器输入:http://localhost:8100/SPRING-GATEWAY/EUREKA-RIBBON/sayHello,显示如下:

因为我们才用的是自动配置路由,所有这里 url 上的服务名称要全部大写,就是和服务注册中心保存一致。 这里我可以看一下 spring-gate 的启动日志,自动路由名称全部是大写。(个人觉得这里设计的不是很好)。

2019-10-12 16:40:35.870  INFO 97725 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: SPRING-GATEWAY.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:35.890  INFO 97725 --- [ctor-http-nio-2] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-SPRING-GATEWAY
2019-10-12 16:40:35.890  INFO 97725 --- [ctor-http-nio-2] c.netflix.loadbalancer.BaseLoadBalancer  : Client: SPRING-GATEWAY instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=SPRING-GATEWAY,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2019-10-12 16:40:35.895  INFO 97725 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2019-10-12 16:40:35.910  INFO 97725 --- [ctor-http-nio-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: SPRING-GATEWAY.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:35.911  INFO 97725 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client SPRING-GATEWAY initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=SPRING-GATEWAY,current list of Servers=[eureka1.server.com:8100],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8100;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@3b80e99c
2019-10-12 16:40:36.008  INFO 97725 --- [tor-http-nio-10] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:36.009  INFO 97725 --- [tor-http-nio-10] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-EUREKA-RIBBON
2019-10-12 16:40:36.010  INFO 97725 --- [tor-http-nio-10] c.netflix.loadbalancer.BaseLoadBalancer  : Client: EUREKA-RIBBON instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2019-10-12 16:40:36.011  INFO 97725 --- [tor-http-nio-10] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2019-10-12 16:40:36.012  INFO 97725 --- [tor-http-nio-10] c.netflix.config.ChainedDynamicProperty  : Flipping property: EUREKA-RIBBON.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2019-10-12 16:40:36.012  INFO 97725 --- [tor-http-nio-10] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client EUREKA-RIBBON initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=EUREKA-RIBBON,current list of Servers=[eureka1.server.com:8901],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:eureka1.server.com:8901;	Zone:defaultZone;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@19148ab

同样的方式我可以请求 eureka-feign,结果如下:

至此基于服务发现的默认路由规则就搭建完成。

1.6 自定义路由规则

1.6.1 修改 application.yml 配置

server:
  port: 8100
spring:
  application:
    name: spring-gateway
  cloud:
      gateway:
#        discovery:
#          locator:
#            enabled: true # 开启通过服务中心的自动根据 serviceId 创建路由的功能
        routes:
          - id: ribbon-route
            uri: lb://EUREKA-RIBBON
            order: 0
            predicates:
              - Path=/ribbon/**
            filters:
              - StripPrefix=1 #去掉前缀,具体实现参考StripPrefixGatewayFilterFactory
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar
          - id: feign-route
            uri: lb://EUREKA-FEIGN
            order: 0
            predicates:
              - Path=/feign/**
            filters:
              - StripPrefix=1
              - AddResponseHeader=X-Response-Default-Foo, Default-Bar

eureka:
  instance:
    hostname: eureka1.server.com
    lease-renewal-interval-in-seconds: 5
    lease-expiration-duration-in-seconds: 10
  client:
    service-url:
      defaultZone: http://eureka1.server.com:8701/eureka/,http://eureka2.server.com:8702/eureka/,http://eureka3.server.com:8703/eureka/

StripPrefix: 接受一个非负整数,对应的具体实现是 StripPrefixGatewayFilterFactory,做用是去掉前缀,整数对应层数。在本例中访问的/ribbon/sayHello,网关服务向后转发请求的时候会去掉/ribbon,eureka-ribbon 收到的请求是:/sayHello。eureka-feign 同理。

1.6.2 启动服务

访问http://localhost:8100/ribbon/sayHello和http://localhost:8100/feign/feign/sayHello,如图下图显示:

  • ribbon:

spring cloud 2.x版本 Gateway路由网关教程_第3张图片

  • feign:

spring cloud 2.x版本 Gateway路由网关教程_第4张图片

1.6.3 自定义 Configuration

Spring Cloud Gateway 同时支持 java 的流式 api 的路由定义,可以和 application.yml 配合使用。

package spring.cloud.demo.spring.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RoutesConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){
        return routeLocatorBuilder.routes().route(r -> r.path("/ribbon/**")
                .filters(f -> f.stripPrefix(1)
                        .addRequestHeader("X-Response-Default-Foo", "Default-Bar"))
                .uri("lb://EUREKA-RIBBON")
                .order(0)
                .id("ribbon-route")
        ).build();
    }
}

总结

本文简单实现了 Spring Cloud Gateway 的默认自动路由和自定义路由的网关服务。后面会继续更新 Spring Cloud Gateway 的其他功能,敬请期待!

代码地址

gitHub 地址[5]


《Srping Cloud 2.X小白教程》目录

  • spring cloud 2.x 版本 Eureka Server 服务注册中心教程[6]
  • spring cloud 2.x 版本 Eureka Client 服务提供者教程[7]
  • spring cloud 2.x 版本 Ribbon 服务发现教程(内含集成 Hystrix 熔断机制)[8]
  • spring cloud 2.x 版本 Feign 服务发现教程(内含集成 Hystrix 熔断机制)[9]
  • spring cloud 2.x 版本 Zuul 路由网关教程[10]
  • spring cloud 2.x 版本 config 分布式配置中心教程[11]
  • spring cloud 2.x 版本 Hystrix Dashboard 断路器教程[12]
  • spring cloud 2.x 版本 Gateway 路由网关教程[13]

  • 写作不易,转载请注明出处,喜欢的小伙伴可以关注公众号查看更多喜欢的文章。
  • 联系方式:[email protected]

参考资料

[1]

eureka-server: https://juejin.im/post/5d8194a2e51d4561ea1a9506

[2]

eureka-client: https://juejin.im/post/5d82061be51d4561f95eeaf5

[3]

eureka-ribbon: https://juejin.im/post/5d82ef25f265da03f12e920f

[4]

eureka-feign: https://juejin.im/post/5d82061be51d4561f95eeaf5

[5]

gitHub地址: https://github.com/fengfujie25/spring-cloud-demo/tree/master/sprin-gateway

[6]

spring cloud 2.x版本 Eureka Server服务注册中心教程: https://juejin.im/post/5d8194a2e51d4561ea1a9506

[7]

spring cloud 2.x版本 Eureka Client服务提供者教程: https://juejin.im/post/5d82061be51d4561f95eeaf5

[8]

spring cloud 2.x版本 Ribbon服务发现教程(内含集成Hystrix熔断机制): https://juejin.im/post/5d82ef25f265da03f12e920f

[9]

spring cloud 2.x版本 Feign服务发现教程(内含集成Hystrix熔断机制): https://juejin.im/post/5d82061be51d4561f95eeaf5

[10]

spring cloud 2.x版本 Zuul路由网关教程: https://juejin.im/post/5d8451bbf265da03da24cf7c

[11]

spring cloud 2.x版本 config分布式配置中心教程: https://juejin.im/post/5d8860cb6fb9a06aeb10fc3e

[12]

spring cloud 2.x版本 Hystrix Dashboard断路器教程: https://juejin.im/post/5d898a366fb9a06b0c08a6df

[13]

spring cloud 2.x版本 Gateway路由网关教程: https://juejin.im/post/5da191fd51882555704c887b

你可能感兴趣的:(spring,cloud,spring,cloud)