Spring Cloud入门教程 - Zuul实现API网关和请求过滤
简介
Zuul是Spring Cloud提供的api网关和过滤组件,它提供如下功能:
- 认证
- 过滤
- 压力测试
- Canary测试
- 动态路由
- 服务迁移
- 负载均衡
- 安全
- 静态请求处理
- 动态流量管理
在本教程中,我们将用zuul,把web端的请求/product
转发到对应的产品服务上,并且定义一个pre过滤器来验证是否经过了zuul的转发。
基础环境
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
项目源码
Gitee码云
创建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 Spring Milestones 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
类:
package cn.zxuqian;import cn.zxuqian.filters.PreFilter;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.zuul.EnableZuulProxy;import org.springframework.context.annotation.Bean;@EnableZuulProxy@EnableDiscoveryClient@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public PreFilter preFilter() { return new PreFilter(); }}
这里使用了@EnableZuulProxy
来指定使用zuul的反向代理,把我们的请求转发到对应的服务器上。然后启用了eureka
的服务发现。Zuul默认也会使用Ribbon做负载均衡,所以可以通过eureka发现已注册的服务。PreFilter
是一个预过滤器,用来在request请求被处理之前进行一些操作,它的代码如下:
package cn.zxuqian.filters;import com.netflix.zuul.ZuulFilter;import com.netflix.zuul.context.RequestContext;import com.netflix.zuul.exception.ZuulException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.servlet.http.HttpServletRequest;public class PreFilter extends ZuulFilter { private static Logger log = LoggerFactory.getLogger(PreFilter.class); @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info(String.format("%s 方式请求 %s", request.getMethod(), request.getRequestURL().toString())); return null; }}
filterType
- Zuul内置的filter类型有四种,pre
, route
,post
,error
,分别代表请求处理前,处理时,处理后和出错后。filterOrder
- 指定了该过滤器执行的顺序。shouldFilter
- 是否开启此过滤器。run
- 过滤器的业务逻辑。这里只是简单的log了一下reqeust的请求方式和请求的路径。
接下来,在我们的配置中心的git仓库中创建zuul-server.yml
文件,并添加如下配置:
server: port: 8083zuul: 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")public String productList() { log.info("Access to /products endpoint"); return "外套,夹克,毛衣,T恤";}
这里@RequestMapping
匹配的路径改为了/list
,之前是/products
。
更新web客户端
在我们的web客户端的ProductService
中添加一个新的方法:
public String productListZuul() { return this.restTemplate.getForObject("http://zuul-server/product/list", String.class);}
这次我们直接请求zuul-server
服务,然后由它把我们的请求反射代理到product-service
服务。最后在ProductController
中添加一个请求处理方法:
@RequestMapping("/product/list")public String productListZuul() { return productService.productListZuul();}
用来处理/product/list
请求,然后调用ProductService
类中的方法。
测试
使用mvn spring-boot:run
启动configServer
,registry
, zuulServer
, productService
,web
这几个工程,然后启动第二个productService
,使用SERVER_PORT=8082 spring-boot:run
。
访问几次http://localhost:8080/product/list
,然后除了会在浏览器看到返回的结果,我们还会在zuulServer
的命令行窗口中看到如下字样:
GET 方式请求 http://xuqians-imac:8083/product/list
然后在两个productService
的命令行窗口中,我们还会看到随机出现的
Access to /products endpoint
说明zuulServer
也会自动进行负载均衡。
欢迎访问我的博客张旭乾的博客
大家有什么想法欢迎来讨论。