You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Zuul is an L7 application gateway that provides capabilities for dynamic routing, monitoring, resiliency, security, and more. Please view the wiki for usage, information, HOWTO, etc https://github.com/Netflix/zuul/wiki
Spring Cloud Zuul 是Spring Cloud Netflix 子项目的核心组件之一,可以作为微服务架构中的API网关使用,支持动态路由与过滤功能,本文将对其用法进行详细介绍。
Zuul简介
摘一段 Zuul 官网上的简介:
API网关为微服务架构中的服务提供了统一的访问入口,客户端通过API网关访问相关服务。API网关的定义类似于设计模式中的门面模式,它相当于整个微服务架构中的门面,所有客户端的访问都通过它来进行路由及过滤。它实现了请求路由、负载均衡、校验过滤、服务容错、服务聚合等功能。
本篇将创建3个服务:
本篇中Spring Boot版本为 2.2.4.RELEASE,Spring Cloud版本为Hoxton.SR5。
创建zuul-proxy模块
在pom.xml中添加相关依赖:
在application.yml中进行配置:
在启动类上添加@EnableZuulProxy注解来启用Zuul的API网关功能:
创建user-service模块
在pom.xml中添加相关依赖:
在application.yml中进行配置:
在启动类上添加@EnableDiscoveryClient注解开启服务注册/发现功能:
增加一个测试用的Controller:
创建product-service模块
跟创建product-service模块 大同小异,这里就不赘述了。
Zuul常用功能演示
启动相关服务
这里我们通过启动eureka-server,两个user-service,product-service和zuul-proxy来演示Zuul的常用功能。
服务启动后打开 http://localhost:8761/ 显示如下:
配置路由规则
我们可以通过修改application.yml中的配置来配置路由规则,这里我们将匹配
/userService/**
的请求路由到user-service服务上去,匹配/productService/**
的请求路由到product-service上去,如下:验证一下:
默认路由规则
Zuul和Eureka结合使用,可以实现路由的自动配置,自动配置的路由以服务名称为匹配路径,相当于如下配置:
验证一下:
如果不想使用默认的路由规则,可以添加以下配置来忽略默认路由配置:
负载均衡功能
多次调用 http://localhost:8080/api-gateway/user-service/api/echo/world 进行测试,可以发现运行在8081的user-service服务 多个实例交替出现。
配置访问前缀
我们可以通过以下配置来给网关路径添加前缀,此处添加了
api-gateway
前缀,这样我们需要访问http://localhost:8080/api-gateway/user-service/api/echo/world 才能访问到user-service中的接口。Header过滤及重定向添加Host
Zuul在请求路由时,默认会过滤掉一些敏感的头信息,以下配置可以防止路由时的Cookie及Authorization的丢失:
Zuul在请求路由时,不会设置最初的host头信息,以下配置可以解决:
查看路由信息
我们可以通过SpringBoot Actuator来查看Zuul中的路由信息。
在zuul-proxy模块 pom.xml中添加相关依赖:
修改application.yaml配置文件,开启查看路由的端点:
通过访问http://localhost:8080/actuator/routes 查看简单路由信息:
通过访问http://localhost:8801/actuator/routes/details查看详细路由信息:
源码下载
spring-cloud-netflix-zuul:https://github.com/TFdream/spring-cloud-tutorials/tree/master/spring-cloud-netflix-zuul
相关资料
The text was updated successfully, but these errors were encountered: