2Zuul 简单应用 · SpringCloud微服务实战 · 看云
导航
本节代码地址
GitHub: https://github.com/xuyisu/fw-sping-cloud/tree/master/fw-cloud-gateways/fw-cloud-gateways-zuul-simple
下面通过一个简单项目带领大家入门,我们直接使用Spring Cloud 封装好的包,本节我们要实现当输入Zuul的地址时可以跳转发哦另一个服务上。如下图
1.新建项目
1.1 添加maven 配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</dependencies>
1.2 添加启动类
启动类中需要添加@EnableZuulProxy注解
@EnableZuulProxy
@SpringBootApplication
public class FwZuulSimpleApplication {
public static void main(String[] args) {
SpringApplication.run(FwZuulSimpleApplication.class, args);
}
}
1.3 添加应用配置
我们给zuul添加转发配置,当输入ip:port/simple 会转发到http://localhost:8764
server:
port: 8678
spring:
application:
name: fw-gateways-zuul-simple
zuul:
routes:
simple:
url: http://localhost:8764 #转发的地址
1.4 启动项目
这里需要fw-cloud-client-eureka服务的支持(8764端口),然后启动当前项目
在Postman 中输入localhost:8678/simple/hello实际上调用的是localhost:8764/hello
2. 运行原理
因为我们开启了@EnableZuulProxy注解,在Spring容器初始化的时候,会将Zuul的相关配置也初始化,Spring Boot提供了ServletRegistrationBean用于注册Servlet,Zuul中有一个类ZuulServlet,在Servlet的service方法中执行各种ZuulFilter。下图是ZuulServlet的生命周期。
zuul把过滤器分为四个阶段,分别是
- pre:主要是在请求路由之前调用,很多验证可以在这里做
- route:在路由请求时候被调用,主要用来转发请求
- post:主要用来处理响应请求
- error:当错误发生时,会经由这个类型的过滤器处理
ZuulServlet的service方法在接收到请求后,会先执行pre阶段的过滤器,再执行routing阶段的过滤器,最后执行post阶段的过滤器,其中routing阶段的过滤器会将请求转发到“源服务”,源服务一般都是第三方服务,也可以是当前集群的其它服务,在实行pre、routing、post阶段发生异常时,会执行error过滤器,整个HTTP请求、响应等数据会被封装到RequestContext对象中。



