Zuul是什么
API Gateway是一个服务器,也可以说是进入系统的唯一节点。这跟面向对象设计模式中的Facade模式很像。API Gateway封装内部系统的架构,并且提供API给各个客户端。它还可能有其他功能,如授权、监控、负载均衡、缓存、请求分片和管理、静态响应处理等。Zuul是Spring cloud的一个组件,作为api-gateway为系统提供反向代理,负载均衡等功能
反向代理
- 新建Spring Cloud项目,在Eureka client依赖的基础上pom.xml引入下面依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
- 在***Application.java文件内开启Zuul代理注解。
@EnableZuulProxy
@SpringBootApplication
public class ZuulServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServerApplication.class, args);
}
}
- 修改application.yml文件,设置端口为4444。同时注册到Eureka Server为http://localhost:1111/eureka/。代理指引/api-a/**的请求到service-A的服务上。
spring:
application:
name: api-gateway
server:
port: 4444
zuul:
routes:
api-a:
path: /api-a/**
serviceId: service-A
eureka:
client:
service-url:
defaultZone: http://localhost:1111/eureka/
- 启动Eureka Server, Eureka Client, Zuul Server,可以看到注册的服务。
- 在浏览器访问localhost:4444/api-a/discovery,得到Eureka Client 返回的结果。
- Eureka Client输出:
负载均衡
- 在上面的例子里,我们将/api-a/**的所有请求转发到service-A的服务上,假设我们有多个service-A服务,那么,Zuul Server将自动向service-A的所有client进行选择转发。
- 新建一个和Eureka Client 一模一样的项目,修改application.yml的注册端口为3333,启动项目。
- 可以看到两个项目都注册到service-A服务上。
- 访问localhost:4444/api-a/discovery两次,得到相同的结果,而在两个client的输出中都得到结果,说明Zuul在两次请求中分别选择了两个client。