业余草 SpringCloud教程 | 第五篇: 路由网关(zuul)(Finchley版本)

在微服务架构中,需要几个基础的服务治理组件,包括服务注册与发现、服务消费、负载均衡、断路器、智能路由、配置管理等,由这几个基础组件相互协作,共同组建了一个简单的微服务系统。一个简答的微服务系统如下图:

Azure (1).png 
注意:A服务和B服务是可以相互调用的,作图的时候忘记了。并且配置服务也是注册到服务注册中心的。

在Spring Cloud微服务系统中,一种常见的负载均衡方式是,客户端的请求首先经过负载均衡(zuul、Ngnix),再到达服务网关(zuul集群),然后再到具体的服。,服务统一注册到高可用的服务注册中心集群,服务的所有的配置文件由配置服务管理(下一篇文章讲述),配置服务的配置文件放在git仓库,方便开发人员随时改配置。

一、Zuul简介

Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/user转发到到user服务,/api/shop转发到到shop服务。zuul默认和Ribbon结合实现了负载均衡的功能。

zuul有以下功能:

  • Authentication
  • Insights
  • Stress Testing
  • Canary Testing
  • Dynamic Routing
  • Service Migration
  • Load Shedding
  • Security
  • Static Response handling
  • Active/Active traffic management

二、准备工作

继续使用上一节的工程。在原有的工程上,创建一个新的工程。

三、创建service-zuul工程

其pom.xml文件如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5  
 6     <groupId>com.forezp</groupId>
 7     <artifactId>service-zuul</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10  
11     <name>service-zuul</name>
12     <description>Demo project for Spring Boot</description>
13  
14     <parent>
15         <groupId>com.forezp</groupId>
16         <artifactId>sc-f-chapter5</artifactId>
17         <version>0.0.1-SNAPSHOT</version>
18     </parent>
19  
20     <dependencies>
21         <dependency>
22             <groupId>org.springframework.cloud</groupId>
23             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
24         </dependency>
25         <dependency>
26             <groupId>org.springframework.boot</groupId>
27             <artifactId>spring-boot-starter-web</artifactId>
28         </dependency>
29         <dependency>
30             <groupId>org.springframework.cloud</groupId>
31             <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
32         </dependency>
33     </dependencies>
34 </project>

在其入口applicaton类加上注解@EnableZuulProxy,开启zuul的功能:

 1 @SpringBootApplication
 2 @EnableZuulProxy
 3 @EnableEurekaClient
 4 @EnableDiscoveryClient
 5 public class ServiceZuulApplication {
 6  
 7     public static void main(String[] args) {
 8         SpringApplication.run( ServiceZuulApplication.class, args );
 9     }
10 }

加上配置文件application.yml加上以下的配置代码:

 1 eureka:
 2   client:
 3     serviceUrl:
 4       defaultZone: http://localhost:8761/eureka/
 5 server:
 6   port: 8769
 7 spring:
 8   application:
 9     name: service-zuul
10 zuul:
11   routes:
12     api-a:
13       path: /api-a/**
14       serviceId: service-ribbon
15     api-b:
16       path: /api-b/**
17       serviceId: service-feign

首先指定服务注册中心的地址为http://localhost:8761/eureka/,服务的端口为8769,服务名为service-zuul;以/api-a/ 开头的请求都转发给service-ribbon服务;以/api-b/开头的请求都转发给service-feign服务;

依次运行这五个工程;打开浏览器访问:http://localhost:8769/api-a/hi?name=forezp ;浏览器显示:

hi forezp,i am from port:8762

打开浏览器访问:http://localhost:8769/api-b/hi?name=forezp ;浏览器显示:

hi forezp,i am from port:8762

这说明zuul起到了路由的作用

四、服务过滤

zuul不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程;

 1 @Component
 2 public class MyFilter extends ZuulFilter {
 3  
 4     private static Logger log = LoggerFactory.getLogger(MyFilter.class);
 5     @Override
 6     public String filterType() {
 7         return "pre";
 8     }
 9  
10     @Override
11     public int filterOrder() {
12         return 0;
13     }
14  
15     @Override
16     public boolean shouldFilter() {
17         return true;
18     }
19  
20     @Override
21     public Object run() {
22         RequestContext ctx = RequestContext.getCurrentContext();
23         HttpServletRequest request = ctx.getRequest();
24         log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
25         Object accessToken = request.getParameter("token");
26         if(accessToken == null) {
27             log.warn("token is empty");
28             ctx.setSendZuulResponse(false);
29             ctx.setResponseStatusCode(401);
30             try {
31                 ctx.getResponse().getWriter().write("token is empty");
32             }catch (Exception e){}
33  
34             return null;
35         }
36         log.info("ok");
37         return null;
38     }
39 }
  • filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下: 
    • pre:路由之前
    • routing:路由之时
    • post: 路由之后
    • error:发送错误调用
    • filterOrder:过滤的顺序
    • shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
    • run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。

这时访问:http://localhost:8769/api-a/hi?name=forezp ;网页显示:

token is empty

访问 http://localhost:8769/api-a/hi?name=forezp&token=22 ; 
网页显示:

hi forezp,i am from port:8762

本文源码下载: 
https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter5

五、参考资料:

http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html

业余草微信公众号

感谢您的关注!可加QQ1群:135430763,QQ2群:454796847,QQ3群:187424846。QQ群进群密码:xttblog,想加微信群的朋友,可以微信搜索:xmtxtt,备注:“xttblog”,添加助理微信拉你进群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作可添加助理微信进行沟通!

原文地址:https://www.cnblogs.com/panda2/p/9419080.html