首页 > 技术文章 > Spring Cloud Gateway---服务化网关服务

dreamstar99 2020-12-10 17:40 原文

写在前面 本文参考以下文章,请参考原文

 springcloud(十六):服务网关 Spring Cloud GateWay 服务化和过滤器

服务化网关服务

前两篇的例子中是服务网关代理单个服务的使用语法,Spring Cloud Gateway是通过配置yml文件来实现网关的服务路由功能。其实呢,在Spring Cloud 微服务体系中,网关服务需要代理很多服务,通过这样配置的方式会很麻烦。其实呢,是可以不这么麻烦的。我们可以把网关服务作为一个基本的服务注册到服务注册中心,Spring Cloud Gateway 提供了一种默认转发的能力,只要将 Spring Cloud Gateway 注册到服务中心,Spring Cloud Gateway 默认就会代理服务中心的所有服务。

1.准备服务注册中心eureka-server 和 网关内部的微服务  eureka-client 和  eureka-client-1 请参考 Spring Cloud Eureka 服务治理--服务消费 ,Spring Cloud Eureka 服务治理--服务消费

2.把网关服务注册到服务注册中心eureka-server

step1.给spring-cloud-gateway添加起步依赖 spring-cloud-starter-netflix-eureka-client

step2.修改配置文件

server:
  port: 8080
spring:
  application:
    name: spring-cloud-gateway
  cloud:
    gateway:
     discovery:
        locator:
         enabled: true
eureka:
  client:
    service-url:
      defaultZone: http://localhost:1001/eureka/
  • spring.cloud.gateway.discovery.locator.enabled:是否与服务注册中心的发现组件功能进行结合,通过 serviceId 转发到具体的服务实例。默认为 false,设为 true 便开启通过服务注册中心的自动根据 serviceId 创建路由的功能
  • eureka.client.service-url.defaultZone:指定注册中心的地址,以便使用服务发现功能。

3.验证服务路由功能:将 Spring Cloud Gateway 注册到服务中心之后,网关会自动代理所有的在注册中心的服务,访问这些服务的语法为 http://网关地址:端口/服务中心注册 serviceId/具体的url

注意这里的serviceId是服务注册中心的serviceId, 不是在微服务配置文件里的spring.application.name值,不过一般serviceId是spring.application.name全大写。

 比如要访问http://localhost:2001/discoveryClient ,通过网关服务来访问就是:http://localhost:8080/EUREKA-CLIENT/discoveryClient。可以看到两次访问,页面返回结果一致,证明服务网关转发成功。

4.验证均衡负载

启动eureka-client-1,它提供和eureka-client微服务一样的服务/discoveryClient,共消费方调用。只不过 eureka-client返回:Services: [] ,而eureka-client-1返回this is client 2 Services:[]。启动后可以在服务注册中心看到有两个名为 EUREKA-CLIENT 的服务。

多次访问 http://localhost:8080/EUREKA-CLIENT/discoveryClient,就会看到eureka-client-1和eureka-client-1的返回结果交替出现,说明后端服务自动进行了均衡负载。

 

推荐阅读