Spring Cloud入门教程之Zuul实现API网关与请求过滤
简介
Zuul是Netflix基于JVM的路由器和服务器端负载均衡器。最常用的场景是替换Nginx反向代理后台微服务供前端UI访问。
Zuul使用Ribbon来定位一个通过发现转发的实例,所有请求都以hystrix命令执行,所以故障将显示在Hystrix指标中。
注:Zuul不包括发现客户端,因此对于基于服务ID的路由,需要在类路径中提供其中一个路由
Zuul是SpringCloud提供的api网关和过滤组件,它提供如下功能:
- 认证
- 过滤
- 压力测试
- Canary测试
- 动态路由
- 服务迁移
- 负载均衡
- 安全
- 静态请求处理
- 动态流量管理
在本教程中,我们将用zuul,把web端的请求/product转发到对应的产品服务上,并且定义一个pre过滤器来验证是否经过了zuul的转发。
基础环境
- JDK1.8
- Maven3.3.9
- IntelliJ2018.1
- Git
项目源码
点击这里
创建Zuul服务
在IntelliJ中创建一个maven项目:
- cn.zxuqian
- apiGateway
然后在pom.xml中添加如下代码:
4.0.0 cn.zxuqian apiGateway 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE org.springframework.cloud spring-cloud-starter-netflix-zuul org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-config org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-dependencies Finchley.M9 pom import 1.8 org.springframework.boot spring-boot-maven-plugin spring-milestones SpringMilestones https://repo.spring.io/libs-milestone false
需要注意的是,Spring官网的教程给的zuul的artifactId为spring-cloud-starter-zuul,这个是旧版zuul的名字,在我们的Finchley.M9版本中已经更名为spring-cloud-starter-netflix-zuul。
添加src/main/resources/bootstrap.yml文件,指定spring.application.name:
spring: application: name:zuul-server
创建cn.zxuqian.Application类:
packagecn.zxuqian; importcn.zxuqian.filters.PreFilter; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.cloud.client.discovery.EnableDiscoveryClient; importorg.springframework.cloud.netflix.zuul.EnableZuulProxy; importorg.springframework.context.annotation.Bean; @EnableZuulProxy @EnableDiscoveryClient @SpringBootApplication publicclassApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(Application.class,args); } @Bean publicPreFilterpreFilter(){ returnnewPreFilter(); } }
这里使用了@EnableZuulProxy来指定使用zuul的反向代理,把我们的请求转发到对应的服务器上。然后启用了eureka的服务发现。Zuul默认也会使用Ribbon做负载均衡,所以可以通过eureka发现已注册的服务。PreFilter是一个预过滤器,用来在request请求被处理之前进行一些操作,它的代码如下:
packagecn.zxuqian.filters; importcom.netflix.zuul.ZuulFilter; importcom.netflix.zuul.context.RequestContext; importcom.netflix.zuul.exception.ZuulException; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importjavax.servlet.http.HttpServletRequest; publicclassPreFilterextendsZuulFilter{ privatestaticLoggerlog=LoggerFactory.getLogger(PreFilter.class); @Override publicStringfilterType(){ return"pre"; } @Override publicintfilterOrder(){ return1; } @Override publicbooleanshouldFilter(){ returntrue; } @Override publicObjectrun()throwsZuulException{ RequestContextctx=RequestContext.getCurrentContext(); HttpServletRequestrequest=ctx.getRequest(); log.info(String.format("%s方式请求%s",request.getMethod(),request.getRequestURL().toString())); returnnull; } }
filterType-Zuul内置的filter类型有四种,pre,route,post,error,分别代表请求处理前,处理时,处理后和出错后。
filterOrder-指定了该过滤器执行的顺序。
shouldFilter-是否开启此过滤器。
run-过滤器的业务逻辑。这里只是简单的log了一下reqeust的请求方式和请求的路径。
接下来,在我们的配置中心的git仓库中创建zuul-server.yml文件,并添加如下配置:
server: port:8083 zuul: routes: products: path:/product/** serviceId:product-service
这里配置了zuul的端口为8083,然后映射所有/product/的请求到我们的product-service服务上。如果不配置serviceId,那么products这个Key就会默认作为ServiceId,而我们的例子中,ServiceId包括了-,所以在下边显示指定了ServiceId。配置完成后提交到git。
更新productService
productService的uri做了一点改动,使其更符合rest风格:
@RequestMapping("/list") publicStringproductList(){ log.info("Accessto/productsendpoint"); return"外套,夹克,毛衣,T恤"; }
这里@RequestMapping匹配的路径改为了/list,之前是/products。
更新web客户端
在我们的web客户端的ProductService中添加一个新的方法:
publicStringproductListZuul(){ returnthis.restTemplate.getForObject("http://zuul-server/product/list",String.class); }
这次我们直接请求zuul-server服务,然后由它把我们的请求反射代理到product-service服务。最后在ProductController中添加一个请求处理方法:
@RequestMapping("/product/list") publicStringproductListZuul(){ returnproductService.productListZuul(); }
用来处理/product/list请求,然后调用ProductService类中的方法。
测试
使用mvnspring-boot:run启动configServer,registry,zuulServer,productService,web这几个工程,然后启动第二个productService,使用SERVER_PORT=8082spring-boot:run。
访问几次http://localhost:8080/product/list,然后除了会在浏览器看到返回的结果,我们还会在zuulServer的命令行窗口中看到如下字样:
GET方式请求http://xuqians-imac:8083/product/list
然后在两个productService的命令行窗口中,我们还会看到随机出现的
Accessto/productsendpoint
说明zuulServer也会自动进行负载均衡。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。