什么是zuul
Zuul是微服务系统的网关组件,是从设备和网站到Netflix流应用程序后端的所有请求的前门。作为边缘服务应用程序,Zuul旨在实现动态路由,监控,弹性和安全性。zuul是一个网关和负载均衡器,在通过ribbon或者feign实现了客户端负载均衡之后,zuul在服务端实现负载均衡。zuul支持用任何JVM语言来编写规则和过滤条件。通过服务网关统一向外系统提供REST API的过程中,除了具备服务路由、均衡负载功能之外,它还具备了权限控制等功能。
为什么要使用微服务网关
在微服务框架下可能有很多个微服务,如果不是用网关实现动态路由,监控,弹性和安全性,那么客户端调用不同微服务,就要请求多个微服务,不仅会增加客户端的复杂性,也有可能会出现跨域请求,且认证相对复杂,每一个微服务都需要单独认证一次,会使后期重构变得复杂(比如后端2个微服务合并成一个微服务,那么客户端的请求也需要发生改变,那客户端也需要重构,无形中增加了开发成本)。
zuul的使用
0.前期准备
在springcloud项目里创建一个api-gateway模块,加入注册中心进行服务化
在pom.xml文件中加入相关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
1.修改配置文件的配置信息
server.port=38763
spring.application.name=api-gateway
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=config-server
spring.cloud.config.profile=dev
eureka.client.service-url.defaultZone=http://localhost:38761/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#zuul的地址映射
#规则:
#例如:http://localhost:38763/zuul/env
#映射为:http://127.0.0.1:38763/env
zuul.routes.zuul.path=/zuul/**
zuul.routes.zuul.url=http://127.0.0.1:38763
#config的地址映射
#规则:
#例如:http://localhost:38763/config/api-gateway-dev.yml
#映射为:http://127.0.0.1:38762/api-gateway-dev.yml
zuul.routes.config.path=/config/**
zuul.routes.config.url=http://127.0.0.1:38762
2.启动类添加相关注解@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
@EnableZuulProxy
@Slf4j
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
log.info("ApiGatewayApplication启动");
}
}
3.启动程序
在讲配置中心时,讲过可以通过http://127.0.0.1:38762/api-gateway-dev.yml访问远程仓库上的api-gateway-dev.yml配置文件信息,现在通过网关去访问该配置http://localhost:38763/config/api-gateway-dev.yml可以看到页面打印出来的配置信息都是
env: dev
可以看到网关在访问http://localhost:38763/config/api-gateway-dev.yml时,根据配置文件里的映射规则将http://localhost:38763/config/映射为了http://127.0.0.1:38762/。
4.改造映射
结合Eureka进行路由映射,依赖服务发现
zuul.routes.config.path=/config/**
zuul.routes.config.service-id=config-server
path表示映射的路由规则,service-id表示注册到eureka服务端的实例名称。
重启服务,依旧访问http://localhost:38763/config/api-gateway-dev.yml可以看到和url映射一样,也是可以对http://127.0.0.1:38762/api-gateway-dev.yml进行访问。
5.可能出现的错误
com.netflix.zuul.exception.ZuulException: Hystrix Readed time out
根据报错信息可以看出是zuul等待超时
解决办法
在配置文件中加入
zuul.host.socket-timeout-millis=60000
zuul.host.connect-timeout-millis=10000
ribbon.ReadTimeout= 60000
自定义等待时长。
zuul也集成了熔断功能,本文主要介绍了zuul的路由功能,至于zuul的熔断功能、过滤功能等将会在后续文章中介绍。