Zuul的主要功能是路由转发和过滤器。

zuul默认和Ribbon结合实现了负载均衡的功能。

  引入网关前后调用流程的变化

 

  在微服务架构中,后端服务往往不直接开放给调用端,而是通过一个API网关根据请求的url,路由到相应的服务。网关直接与调用方通信进行权限控制,后将请求均衡分发给后台服务端

  引入网关后,调用流程的变化。不使用网关的情况:

微服务网关隔离 微服务网关搭建_ide

  引入网关后:

  

微服务网关隔离 微服务网关搭建_spring_02

  搭建单节点的Zuul

  这里会把zuul注册到Eureka上

  创建子Module gateway-zuul

  添加maven依赖

<!-- eureka client 依赖  . Eureka不是必须的 ,在没有注册中心的情况下,也可以使用zuul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    
        <!-- zuul 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

  官方Note: the Zuul starter does not include a discovery client, so, for routes based on service IDs, you need to provide one of those on the classpath as well (Eureka is one choice). 因为我们使用serverID去做路由,所以我们这里引入了Eureka

  启动类添加注解 @EnableZuulProxy

@SpringBootApplication
@EnableZuulProxy
public class GatewayZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayZuulApplication.class, args);
    }

}

  通过注解@EnableZuulProxy声明一个zuul代理,代理整合Ribbon来定位注册在Eureka上的微服务,同时还整合hystrix实现容错,所有经过zuul的请求都会在Hystrix命令中执行。

  配置文件application.yml

server:
  port: 4534

spring:
  application:
      name: gateway-zuul

eureka:
  client:
     service-url:
        defaultZone: http://Jim:land123@localhost:8761/eureka
  instance:
     instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}

  观察上面的配置文件,是没有zuul相关的配置的,我们仅仅添加了一个zuul的依赖,同时将zuul注册到Eureka上。 至此,一个单节点的最精简版的zuul就搭建完成

  网关功能-路由规则测试

  1、启动注册中心Eureka Server 项目 discovery-eureka

  2、启动服务提供者provider-user
  3、启动服务消费者 consumer-movie-ribbon
  4、启动zuul网关gateway-zuul
  

微服务网关隔离 微服务网关搭建_微服务网关隔离_03

  验证下路由转发的功能

  知道zuul服务的启动端口为 4534 ,通过zuul访问服务提供者提供的服务看下

       http://localhost:4534/provider-user/user/3


   通过zuul访问服务消费者
       http://localhost:4534/consumer-movie-ribbon/movie/4

   服务被转发到了consumer-movie-ribbon微服务中

   默认情况下,zuul会代理所有注册在Eureka Server上的微服务,并且Zuul的路由规则为http://zuul_host:zuul_port/微服务在EurekaServer上的serviceId/** 被转发到serviceId对应的微服务上。

   网关功能-负载均衡测试

  1、启动注册中心Eureka Server 项目 discovery-eureka

      2、启动多个服务提供者provider-user ,在sts中换个端口,可启动多个,再加个8901端口上的服务
          3、启动服务消费者 consumer-movie-ribbon
     4、启动zuul网关gateway-zuul
  访问两次服务提供者提供的服务,观察后台日志

  网关功能-Hystrix监控测试

  

微服务网关隔离 微服务网关搭建_ide_04