一.前言
1.介绍
- 在微服务中如果没有网关,一个客户端完成一个业务动作,可能需要调用多个微服务接口,而且每个微服务都需要安全认证,加大了客户端的复杂性。
- zuul是一个客户端和服务端之间的中间层,客户端所有的请求流量都经过zuul做分发,zuul代理了后端的微服务,对于客户端来说屏蔽了后端微服务调用的复杂性;当后端微服务进行业务调整,只需要在zuul中调整路由规则就可以了,客户端和服务端得到了良好解耦合
- Zuul也是一款由Netflix开发的微服务网关开源软件,和Netflix开发的Eureka,Ribbon和Hystrix配合使用
- Zuul主要功能为路由器和过滤器,这篇主要介绍路由功能
2.项目准备
- 项目地址完整例子传送门
- 此篇文章用到项目模块:
- 模块介绍:
1.eureka-server-standalone
: 提供注册中心的服务
2.zuul-gateway
:提供zuul网关功能,注册到eureka
服务中心
3.zuul-consumer
:提供接口调用,具有hystrix
熔断功能,和ribbon
负载均衡功能,注册到eureka
服务中心
二.创建zuul服务
- Spring Cloud集成Zuul代理,可以默认代理注册中心的服务。从而避免了后端每个微服务都需要独立管理CORS和身份验证问题。
1.官网资料
2.创建 zuul-gateway
项目
- 在启动类中
ZuulGatewayApplication.java
中
@EnableZuulProxy
@SpringCloudApplication
public class ZuulGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulGatewayApplication.class, args);
}
}
加入
@EnableZuulProxy
表示此项目启动zuul代理功能
加入@SpringCloudApplication
表示此项目启动断路由,eureka
注册功能
- 在pom.xml中
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
引入
zuul
和eureka-client
依赖,其中zuul
包含了hystrix
,actuator
,ribbon
等功能,见下图
- 配置文件
application.yml
中
spring:
application:
name: Zuul-Gateway
server:
port: 9001
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
management:
endpoints:
web:
exposure:
include: '*'
management.endpoints.web.exposure.include
:打开actuator
的监控端口,,默认只打开了health
,info
的监控监控点*
代表全部打开,此举是用于查看/routes
接口,返回此zuul
代理了多少服务,以及路由规则;如下:
-
启动验证
1.依次启动eureka-server-standalone
端口为8760,zuul-gateway
端口为9001
2.zuu
项目有对外暴露的actuator
端点/routes
:获取zuul项目的代理服务列表
/routes/details
:zuul项目的代理服务详情3.访问
http://localhost:9001/actuator/routes
,可见如下,只代理了自己的服务{ "/zuul-gateway/**": "zuul-gateway"}
4.也可以查看详情
localhost:9001/actuator/routes/details
{ "/zuul-gateway/**": { "id": "zuul-gateway", "fullPath": "/zuul-gateway/**", "location": "zuul-gateway", "path": "/**", "prefix": "/zuul-gateway", "retryable"<