SpringCloud组件: GateWay整合Eureka转发服务请求

在上一篇文章Spring Cloud GateWay 路由转发规则介绍中我们讲解了SpringCloud Gateway内部提供的断言、谓语,让我们可以组合更精确的业务场景进行请求,既然SpringCloud GateWay担任了网关的角色,在之前Zuul可以通过服务名进行自动转发,SpringCloud Gateway是否可以实现自动转发呢?

初始化Gateway服务

Spring Cloud Gateway可以根据配置的断言、谓语进行满足条件转发,也可以自动同步服务注册中心的服务列表进行指定serviceId前缀进行转发,这里的serviceId是业务服务的spring.application.name配置参数。

SpringCloud 版本控制依赖

SpringCloud的版本依赖添加到pom.xml内,如下所示:

//...
<properties>
  <java.version>1.8</java.version>
  <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<!--Spring Cloud 版本控制-->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
//...

我们本章使用Eureka作为服务注册中心来完成服务请求转发讲解,需要把Spring Cloud Gateway网关项目作为一个Client注册到Eureka Server,先来看下添加的依赖,pom.xml如下所示:

//...
<dependencies>
  <!--Spring Cloud Gateway-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
  </dependency>
  <!--Eureka Client-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
</dependencies>
//....

接下来我们需要开启Gateway服务注册中心的发现配置,开启后才能自动同步服务注册中心的服务列表application.yml配置文件如下所示:

# 服务名称
spring:
  application:
    name: spring-cloud-gateway
  # 开启 Gateway 服务注册中心服务发现
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
# Eureka Server 配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
# 配置Gateway日志等级,输出转发细节信息
logging:
  level:
    org.springframework.cloud.gateway: debug

配置参数解释如下所示:

  • spring.application.name:服务名
  • spring.cloud.gateway.discovery.locator.enabled:开启SpringCloud Gateway的注册中心发现配置,开启后可自动从服务注册中心拉取服务列表,通过各个服务的spring.application.name作为前缀进行转发,该配置默认为false
  • eureka.client.service-url.defaultZone:配置Eureka Server默认的空间地址
  • logging.level.org.springframework.cloud.gateway:设置SpringCloud Gateway日志等级为debug,用于输出转发的细节日志,方便查看细节流程。

注册网关到Eureka

在入口类添加对应的注解,开启服务自动注册,如下所示:

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudGatewayApplication.class, args);
    }
}

服务注册中心

对应上面网关配置的Eureka Server的地址,我们需要添加对应的配置,pom.xml如下所示:

//...
<dependencies>
  <!--Eureka Server-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  </dependency>
</dependencies>
//...

添加依赖后对Eureka Server进行配置,配置文件application.yml如下所示:

# 服务名
spring:
  application:
    name: sample-eureka-server
# 端口号    
server:
  port: 10000

# Eureka 配置信息
eureka:
  client:
    service-url:
      defaultZone: http://localhost:${server.port}/eureka/
    fetch-registry: false
    register-with-eureka: false

这里我们修改默认的端口号为10000,为了匹配在网关项目的配置信息,至于fetch-registryregister-with-eureka可以去我之前的文章查看,SpringCloud组件:将服务提供者注册到Eureka集群

开启Eureka Server

我们通过@EnableEurekaServer注解来开启服务,如下所示:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

网关服务注册中心我们都已经准备好了,下面我们可以编写业务逻辑服务,来验证SpringCloud Gateway具体是否可以根据serviceId进行转发请求。

单服务

我们简单编写一个GET请求地址,输出字符串信息,pom.xml添加依赖如下所示:

<dependencies>
  <!--Web-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!--Eureka Client-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  </dependency>
</dependencies>

配置文件application.yml如下所示:

# 服务名
spring:
  application:
    name: user-service
# 注册到Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
# 服务端口号
server:
  port: 9090

配置该服务的服务名称为user-service,这里对应SpringCloud GatewayserviceId

注册服务到Eureka

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class UserServiceApplication {
    /**
     * logger instance
     */
    static Logger logger = LoggerFactory.getLogger(UserServiceApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
        logger.info("「「「「「用户服务启动完成.」」」」」");
    }

    @GetMapping(value = "/index")
    public String index() {
        return "this is user index";
    }
}

user-service提供了/index的请求地址,当访问时,会对应输出this is user index

测试服务请求转发

接下来我们进行验证,测试顺序如下所示:

第一步:启动Eureka Server

第二步:启动SpringCloud Gateway

启动成功后控制台会打印响应的注册到Eureka的日志信息,如下所示:

DiscoveryClient_SPRING-CLOUD-GATEWAY/192.168.1.56:spring-cloud-gateway: registering service...
Netty started on port(s): 8080

SpringCloud Gateway内部通过Netty完成WebServer的请求转发。

第三步:启动user-service服务

启动成功后控制台打印相应注册日志,如下所示:

DiscoveryClient_USER-SERVICE/192.168.1.56:user-service:9090: registering service...
Tomcat started on port(s): 9090 (http) with context path ''

第四步:测试访问

SpringCloud Gateway会每间隔30秒进行重新拉取服务列表后路由重定义操作,日志信息如下所示:

# Spring Cloud Gateway
RouteDefinition CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY applying {pattern=/SPRING-CLOUD-GATEWAY/**} to Path
RouteDefinition CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY applying filter {regexp=/SPRING-CLOUD-GATEWAY/(?<remaining>.*), replacement=/${remaining}} to RewritePath
RouteDefinition matched: CompositeDiscoveryClient_SPRING-CLOUD-GATEWAY
# User Service
RouteDefinition CompositeDiscoveryClient_USER-SERVICE applying {pattern=/USER-SERVICE/**} to Path
RouteDefinition CompositeDiscoveryClient_USER-SERVICE applying filter {regexp=/USER-SERVICE/(?<remaining>.*), replacement=/${remaining}} to RewritePath
RouteDefinition matched: CompositeDiscoveryClient_USER-SERVICE

通过上面的日志信息我们已经可以推断出SpringCloud Gateway映射spring.application.name的值作为服务路径前缀,不过是大写的,预计我们可以通过http://localhost:8080/USER-SERVICE/index访问到对应的信息。

访问测试如下:

~ curl http://localhost:8080/USER-SERVICE/index
this is user index

通过网关访问具体服务的格式:http://网关IP:网关端口号/serviceId/**

多服务的负载均衡

如果Eureka Server上有两个相同serviceId的服务时,SpringCloud Gateway会自动完成负载均衡。

复制一个user-service服务实例,修改服务端口号,如下所示:

# 服务名称
spring:
  application:
    name: user-service
# Eureka Server
eureka:
  client:
    service-url:
      defaultZone: http://localhost:10000/eureka/
# 服务端口号
server:
  port: 9091

在复制的项目内使用相同的spring.application.name保持serviceId一致,只做端口号的修改,为了区分GateWay完成了负载均衡,我们修改/index请求的返回内容如下所示:

@GetMapping(value = "/index")
public String index() {
  return "this is user lb index";
}

访问http://localhost:8080/USER-SERVICE/index,输出内容如下所示:

this is user lb index
this is user index
this is user lb index
this is user index
...

总结

通过本章的讲解,我们已经对SpringCloud Gateway的转发有一个简单的理解,通过从服务注册中心拉取服务列表后,自动根据serviceId映射路径前缀,同名服务多实例时会自动实现负载均衡。

源码位置

Giteehttps://gitee.com/hengboy/spring-cloud-chapter/tree/master/SpringCloud/spring-cloud-gateway-request-forward

作者个人 博客
使用开源框架 ApiBoot 助你成为Api接口服务架构师

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270