Zuul的主要功能是对请求的路由转发和过滤,路由功能将外部请求转发到具体的微服务实例,过滤功能负载对请求进行校验、服务聚合等操作,Zuul与Eureka整合,将自身注册到服务中心,通过Eureka统一管理从Eureka中获取相应的微服务。
官方文档:
http://projects.spring.io/spring-cloud/spring-cloud.html#_router_and_filter_zuul
https://github.com/Netflix/zuul/wiki
http://cloud.spring.io/spring-cloud-static/Edgware.SR4/single/spring-cloud.html#zuul-developer-guide
以下内容是基于上一节的工程,实现Zuul
源码下载:https://github.com/hnyydp/microservice
(1)、新建一个microservice-zuul-9003
服务,添加zuul依赖:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-zuulartifactId>
dependency>
(2)添加application.yml配置
spring:
application:
name: microservice-zuul
server:
context-path: /
port: 9003
eureka:
client:
service-url:
#集群配置
defaultZone: http://eureka-server-5001.com:5001/eureka/,http://eureka-server-5002.com:5002/eureka/,http://eureka-server-5003.com:5003/eureka/
instance:
instance-id: microservice-zuul-9003.com #自定义服务名称信息
prefer-ip-address: true #访问路径上会显示IP,当应用程序向eureka注册时,它将使用其IP地址而不是其主机名。
(3)在主启动类ZuulGatewayApplication_9003.java
中添加@EnableZuulProxy
启动Zuul路由。
@EnableZuulProxy //开启Zuul路由
@EnableEurekaClient
@SpringBootApplication
public class ZuulGatewayApplication_9003 {
public static void main(String[] args) {
SpringApplication.run(ZuulGatewayApplication_9003.class, args);
}
}
(4)启动Eureka服务和服务提供者和microservice-zuul-9003,分别用正常方式访问和zuul路由访问。
(5)配置路由访问映射规则:
zuul:
prefix: /app #指定一个全局的前缀
ignored-services: microservice-dept #忽略真实服务名
#ignored-services: "*"
routes:
dept-service:
service-id: microservice-dept #真实服务名映射
path: /mydept/**
(7)服务过滤,我们可以自定义过滤器来实现Zuul服务过滤:
@Component
public class MyFilter extends ZuulFilter{
private Logger logger = LoggerFactory.getLogger(MyFilter.class);
@Override
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = context.getRequest();
logger.info(String.format("****Method:%s, URL:%s*****",request.getMethod(),request.getRequestURL().toString()));
return null;
}
// 判断是否需要过滤
@Override
public boolean shouldFilter() {
return true;
}
// 过滤器的优先级,越大越靠后执行
@Override
public int filterOrder() {
return 1;
}
/**
* 过滤器类型:
* pre:路由之前
* routing:路由之时
* post: 路由之后
* error:发送错误调用
*/
@Override
public String filterType() {
return "pre";
}
}