1. Zuul是什么
路由在微服务体系结构的一个组成部分。例如,/
可以映射到您的Web应用程序,/api/users
映射到用户服务,并将/api/shop
映射到商店服务。Zuul是Netflix的基于JVM的路由器和服务器端负载均衡器。
2. 如何使用Zuul
首先,创建一个普通的springboot项目routes-filter-zuul作为myspringcloud项目的子项目,引入zuul的依赖spring-cloud-starter-netflix-zuul
,并在springboot的主类上添加@EnableZuulProxy
注解表示开启zuul的功能。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
@SpringBootApplication
@EnableZuulProxy
public class RoutesFilterZuulApplication {
public static void main(String[] args) {
SpringApplication.run(RoutesFilterZuulApplication.class, args);
}
}
在application.yml中添加路由配置:
spring:
application:
name: routes-filter-zuul
server:
port: 8085
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka
zuul:
routes:
service-feign:
path: /feign/**
serviceId: consumer-feign
service-ribbon:
path: /ribbon/**
serviceId: consumer-ribbon
这里的zuul.routes
以下内容是路由的详细配置,这里的service-feign
和service-ribbon
是自定义的路由名称,可以自己定义,path:/feign/**
表示以feign开头的地址,serviceId:consumer-feign
表示要调用的服务名,与实际服务的名称对应。以下相同表示以ribbon开的地址访问consumer-ribbon服务。
测试:
1.启动eureka服务
2.启动两个provider服务,端口8081,8082
3.启动consumer-feign和consumer-ribbon两个服务
4.启动routes-filter-zuul路由服务
5.在浏览器输入地址:http://localhost:8085/ribbon/hello?name=xinfeng
和http://localhost:8085/feign/hello?name=xinfeng
3. Zuul的过滤器
Zuul不仅仅具有路由转发的功能,它还支持过滤器的功能,如,可以拦截用户请求进行权限校验等。你可以自定义一个过滤器但必须继承自ZuulFilter
。这里定义了一个MyZuulFilter类继承自ZuulFilter并实现了父类的4个方法,使用了@Component注解将该类的实例注入到spring的容器中。
@Component
public class MyZuulFilter extends ZuulFilter {
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String username = request.getParameter("name");
if (username == null) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
ctx.addZuulResponseHeader("content-type","text/html;charset=utf-8");
ctx.setResponseBody("unknown user");
}
return null;
}
}
filterType: 该方法表示过滤器的类型,决定过滤器将在何时执行,该方法的返回值是一个String类型,包含的值有pre、route、post、error
和static
。这里我们返回的是pre,表示在路由之前执行过滤。
filterOrder: 表示过滤器的优先级, 还必须为过滤器定义filterOrder,如果优先级对于过滤器不重要,则过滤器可能具有相同的filterOrder。 filterOrders不需要是顺序的。
shouldFilter: 表示是否需要调用过滤器的run方法,返回true,则调用,返回false,则不调用。
run: 方法中定义需要执行的过滤操作。
测试:
1.启动eureka服务
2.启动两个provider服务,端口8081,8082
3.启动consumer-feign和consumer-ribbon两个服务
4.启动routes-filter-zuul路由服务
5.在浏览器输入地址:http://localhost:8085/feign/hello
和 http://localhost:8085/feign/hello?name=xinfeng
过滤器已生效,当请求参数中不包含name字段,请求被过滤器拦截并返回“unknown user”,当请求参数中包含name字段时过滤器放行。