SpringCloud学习第六篇:Zuul学习(Hoxton.SR4)
一、什么是Zuul
Zuul作为微服务系统的网关组件。所有从设备或网站来的请求都会经过Zuul到达后端,用于构建边界服务,致力于动态路由、过滤、监控、弹性伸缩和安全。Zuul底层利用各种filter来实现如:认证和安全、性能检测、动态路由、压力测试、负载均衡、静态资源处理。
二、Zuul和Nginx的区别
- 相同点
Zuul和Nginx都可以实现负载均衡、反向代理(隐藏真实ip地址),过滤请求,实现网关的效果 - 不同点
Nginx:C语言开发,采用服务器负载均衡
Zuul:java开发,使用eureka+ribbon实现负载均衡。
Nging相对Zuul更加强大,Nginx可以整合一些脚本语言。
三、Zuul学习
3.1、Demo搭建
Zuul的学习是在上一章工程基础之上建立的
- Maven
<dependencies>
<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>
</dependencies>
- application.properties
# Tomcat
server:
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 1104
spring:
application:
name: zuul
eureka:
client:
service-url:
defaultZone: http://localhost:1101/eureka/
instance:
hostname: localhost
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
zuul:
routes:
api-a:
path: /api-a/**
serviceId: web-demo
# api-b:
# path: /api-b/**
# serviceId: service-feign
- 启动入口
@EnableZuulProxy
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class,args);
}
}
- Demo演示
3.2、ZuulFilter
- 创建RequestFilter
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import javax.servlet.http.HttpServletRequest;
import com.netflix.zuul.context.RequestContext;
public class RequestFilter extends ZuulFilter {
//这里可以处理逻辑
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
System.out.println(String.format( request.getMethod(), request.getRequestURL().toString()));
// 对该请求进行路由
ctx.setSendZuulResponse(true);
ctx.setResponseStatusCode(200);
// 设值,让下一个Filter看到上一个Filter的状态
ctx.set("isSuccess", true);
return null;
}
//过滤器类型
//per:前置过滤器、route:负责转发请求到微服务、error:处理请求错误是被调用、post:在route和error过滤器之后调用
@Override
public String filterType() {
return "pre";
}
/**
* 优先级为0,数字越大,优先级越低
*/
@Override
public int filterOrder() {
return 0;
}
//是否执行该过滤器 false为不执行
@Override
public boolean shouldFilter() {
return true;
}
}
- 入口类增加RequestFilter Bean
@Bean
public RequestFilter requestFilter(){
return new RequestFilter();
}