Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能。
本篇基于上一篇的项目
创建Zuul工程
创建新model,pom引入依赖
<!--Eureka依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--Web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--Zuul依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
编写配置文件application.yml
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8769 spring: application: name: service-zuul zuul: routes: api-a: path: /api-a/** serviceId: service-ribbon api-b: path: /api-b/** serviceId: service-feign
以/api-a/ 开头的请求都转发给service-ribbon服务,以/api-b/开头的请求都转发给service-feign服务
在启动类上加上@EnableZuulProxy注解,开启zuul功能
@SpringBootApplication @EnableZuulProxy @EnableEurekaClient public class ServiceZuulApplication { public static void main(String[] args) { SpringApplication.run( ServiceZuulApplication.class, args ); } }
依次运行eureka-server,service-client,service-ribbon,service-feign,service-zuul
访问:http://localhost:8769/api-a/hi?name=fhaha浏览器显示
hi haha ,现在的端口是:8762
访问http://localhost:8769/api-b/hi?name=haha浏览器显示
hi haha ,现在的端口是:8762
服务过滤
zuul还能过滤,做一些简单的安全验证
继续 创建config层MyFilter类
@Component @Slf4j public class MyFilter extends ZuulFilter { @Override public String filterType() { return "pre"; // 可以在请求被路由之前调用 } @Override public int filterOrder() { return 0; // filter执行顺序,通过数字指定 ,优先级为0,数字越大,优先级越低 } @Override public boolean shouldFilter() { return true; // 是否执行该过滤器,此处为true,说明需要过滤 } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString()); String token = request.getParameter("token"); if (StringUtils.isNotBlank(token)) { ctx.setSendZuulResponse(true); //对请求进行路由 ctx.setResponseStatusCode(200); ctx.set("isSuccess", true); return null; } else { ctx.setSendZuulResponse(false); //不对其进行路由 ctx.setResponseStatusCode(400); ctx.setResponseBody("token is empty"); ctx.set("isSuccess", false); return null; } } }
filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型
- pre:路由之前
- routing:路由之时
- post: 路由之后
- error:发送错误调用
ilterOrder:过滤的顺序
shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤
run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问
访问:http://localhost:8769/api-a/hi?name=fhaha浏览器显示
token is empty
访问:http://localhost:8769/api-a/hi?name=forezp&token=22
hi haha ,现在的端口是:8762