SpringCloud Gateway整合Eureka转发服务请求

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

初始化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可以去我之前的文章查看,{% post_path eureka-register-service 将服务注册到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映射路径前缀,同名服务多实例时会自动实现负载均衡。

相关实践学习
部署高可用架构
本场景主要介绍如何使用云服务器ECS、负载均衡SLB、云数据库RDS和数据传输服务产品来部署多可用区高可用架构。
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
相关文章
|
2天前
|
算法 NoSQL API
SpringCloud&Gateway网关限流
SpringCloud&Gateway网关限流
42 7
|
2天前
|
负载均衡 Nacos 数据安全/隐私保护
SpringCloud GateWay 使用
SpringCloud GateWay 使用
23 0
|
2天前
|
缓存 负载均衡 监控
SpringCloud&Eureka理论与入门
SpringCloud&Eureka理论与入门
21 0
|
1天前
|
负载均衡 监控 算法
【微服务 SpringCloud】实用篇 · Eureka注册中心
【微服务 SpringCloud】实用篇 · Eureka注册中心
10 1
|
1天前
|
存储 SpringCloudAlibaba Java
【微服务 SpringCloud】实用篇 · 服务拆分和远程调用
【微服务 SpringCloud】实用篇 · 服务拆分和远程调用
15 2
|
2天前
|
Java 数据安全/隐私保护 Sentinel
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
微服务学习 | Spring Cloud 中使用 Sentinel 实现服务限流
|
2天前
|
Java 微服务 Spring
SpringCloud&Gateway全局过滤器
SpringCloud&Gateway全局过滤器
11 1
|
2天前
|
监控 Java API
第七章 Spring Cloud 之 GateWay
第七章 Spring Cloud 之 GateWay
23 0
|
2天前
|
负载均衡 监控 容灾
【SpringCloud】详解Eureka注册中心
【SpringCloud】详解Eureka注册中心
23 0
|
2天前
|
Java Maven 微服务
第四章 Spring Cloud Netflix 之 Eureka
第四章 Spring Cloud Netflix 之 Eureka
14 0