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

前言

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

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

概念

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

创建Gateway工程

1.1 创建sping boot工程:spring-gateway

1.2 添加pom.xml相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</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服务中心看一下服务是否正常启动,如下如:

截图中红框代表所有服务已经正常启动。
然后新打来浏览器输入: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.springf[email protected]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.springf[email protected]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:

  • feign:

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地址


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

原文地址:https://www.cnblogs.com/fengfujie/p/11820553.html

时间: 2024-08-24 02:53:58

spring cloud 2.x版本 Gateway路由网关教程的相关文章

spring cloud 2.x版本 Gateway自定义过滤器教程

前言 本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 本文基于前两篇文章eureka-server.eureka-client.eureka-ribbon.eureka-feign和spring-gataway的实现. 参考 eureka-server eureka-client eureka-ribbon eureka-feign spring-gateway 概术 Spring Cloud Gateway内部已经提供非常多的过滤器f

spring cloud 2.x版本 Gateway动态路由教程

摘要 本文采用的Spring cloud为2.1.8RELEASE,version=Greenwich.SR3 本文基于前面的几篇Spring cloud Gateway文章的实现. 参考 Gateway路由网关教程 Gateway自定义过滤器教程 前言 写了几篇关于Spring Cloud Gateway的文章后发现,Gateway涉及的知识范围太广了,真是深刻体会了"一入Spring cloud深似海". 现实生产环境中,使用Spring Cloud Gateway都是作为所有流量

spring cloud 2.x版本 Ribbon服务发现教程(内含集成Hystrix熔断机制)

本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 前言 本文基于前两篇文章eureka-server和eureka-client的实现. 参考 eureka-server eureka-client 1 Ribbon工程搭建 1.1 创建spring boot工程:eureka-ribbon 1.2 pom.xml所需要依赖的jar包 <dependency> <groupId>org.springframework.clo

spring cloud 2.x版本 Gateway熔断、限流教程

前言 本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 概术 在高并发应用中,缓存.限流.降级,是我们保护系统应用的三大利器.在开发一些api接口的时候,通常也会在网关层做限流控制,一方面是为了防止大量的请求是服务器过载,导致服务器不可用,另一方面也是防止其他人的恶习网络***. 常见的限流方式,如Hystrix的使用线程池隔离,超过线程池的负载走熔断的逻辑:也有通过滑动的时间窗口来控制流量. 常用的限流算法有,计数器算法.漏桶算法.令牌

Spring Cloud(十一):服务网关 Zuul(过滤器)【Finchley 版】

Spring Cloud(十一):服务网关 Zuul(过滤器)[Finchley 版] 发表于 2018-04-23 |  更新于 2018-05-07 | 在上篇文章中我们了解了 Spring Cloud Zuul 作为网关所具备的最基本功能:路由(Router).本文我们将关注 Spring Cloud Zuul 的另一核心功能:过滤器(Filter). Filter 的作用 我们已经能够实现请求的路由功能,所以我们的微服务应用提供的接口就可以通过统一的 API 网关入口被客户端访问到了.但

spring cloud:Edgware.RELEASE版本hystrix超时新坑

升级到Edgware.RELEASE发现,zuul中不管如何设置hystrix的超时时间均不起作用,仍然是默认的1000ms.  降回低版本后正常,但是低版本的fallback方法中,又拿不到详细异常信息,最终暂时在Edgware.RELEASE中,将hystrix的超时关掉,参考以下配置: ribbon: ReadTimeout: 5000 ConnectTimeout: 5000 MaxAutoRetries: 0 MaxAutoRetriesNextServer: 1 hystrix: c

业余草 SpringCloud教程 | 第九篇: 服务链路追踪(Spring Cloud Sleuth)(Finchley版本)

这篇文章主要讲述服务追踪组件zipkin,Spring Cloud Sleuth集成了zipkin组件. 一.简介 Add sleuth to the classpath of a Spring Boot application (see below for Maven and Gradle examples), and you will see the correlation data being collected in logs, as long as you are logging re

Spring Boot与Spring Cloud技术选型版本对应关系

Spring Boot与Spring Cloud版本严格来将,Boot是以数字作为版本,Cloud是以英语大写字母开头作为版本,这些其实都是伦敦地铁站命名的版本. 一.如何选择Spring Boot版本? github源码地址:https://github.com/spring-projects/spring-boot/wiki springboot2.0新特性:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0

spring cloud 学习(6) - zuul 微服务网关

微服务架构体系中,通常一个业务系统会有很多的微服务,比如:OrderService.ProductService.UserService...,为了让调用更简单,一般会在这些服务前端再封装一层,类似下面这样: 前面这一层俗称为“网关层”,其存在意义在于,将"1对N"问题 转换成了"1对1”问题,同时在请求到达真正的微服务之前,可以做一些预处理,比如:来源合法性检测,权限校验,反爬虫之类... 传统方式下,最土的办法,网关层可以人肉封装,类似以下示例代码: LoginResul