Zuul的主要功能:
1 路由转发
2 过滤器
zuul有以下功能:
Authentication
Insights
Stress Testing
Canary Testing
Dynamic Routing
Service Migration
Load Shedding
Security
Static Response handling
Active/Active traffic management
本章实例工程包括了四个module:
eureka-server 端口8800
zuul-server 端口8801
first-service 端口8802
second-service 端口8803
1路由转发
zuul-server路由转发的功能通过注解@EnableZuulProxy开启Zuul功能:
application.properties的配置文件如下:
zuul.routes.api-a.path=/api-1/**
zuul.routes.api-a.serviceId= FirstService
zuul.routes.api-b.path= /api-2/**
zuul.routes.api-b.serviceId= SecondService
url中包含api-1转发给FirstService,url中包含api-2转发给SecondService。
运行如下:
执行http://localhost:8800/查看注册的service:
下面验证路由的功能:
执行http://localhost:8801/api-1/index:
执行http://localhost:8801/api-2/index:
2 过滤器
zuul-server过滤器的功能是通过继承类ZuulException来实现的。
@Override
public Object run() throws ZuulException {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest httpServletRequest = requestContext.getRequest();
String userName = httpServletRequest.getHeader("user");
if(StringUtils.isEmpty(userName)){
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(401);
requestContext.setResponseBody("user is not login!");
}
return null;
}
下面验证过滤器的功能:
执行localhost:8801/api-1/index
header增加后user后,执行localhost:8801/api-1/index:
代码参考:https://github.com/linghufeixia/springcloud-simplechapter4