正文
1. 概述
本文介绍Zuul的相关的内容,主要包括如下内容
-
服务网关的作用
-
Spring Cloud集成Zuul的demo:包括配置各种各样的路由关系
-
自定义Zuul的Filter
2. 服务网关Zuul的作用
服务网关的作用,其作用类似我们常用Ngnix
-
1 对外提供统一的REST API接口,收缩所有的服务到服务网关后面
-
2 放置到对外访问的前端,可以做权限验证
-
3 可以做均衡负载器
-
4 可以做服务路由的功能
3. Spring Cloud集成Zuul的demo
3.1. 相关的工程说明
cloud-registration-center
注册中心,比较简单,这里代码略
cloud-service-zuul
作为服务方的工程,提供服务的工程,这里代码略。其具体实现方法可以参数
Spring cloud系列一 包含所有基本要素的完整Spring Cloud demo
。这个服务的注册名称为”cloud-service-zuul”。此服务提供一个服务:URL为
http://127.0.0.1:14606/zuul-test/simple
。
cloud-zuul
提供服务网关的功能。本工程我们演示通过各种配置实现访问cloud-zuul的URL达到访问cloud-service-zuul服务接口(URL为
http://127.0.0.1:14606/zuul-test/simple
)的目的
3.2. cloud-zuul工程
3.2.1. pom.xml:
引入zuul的依赖jar
<!-- 引入zuul-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
3.2.2. 启动类ZuulSimpleCloudApplication
@EnableZuulProxy:注解此服务为zuul代理服务
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulSimpleCloudApplication {
public static void main(String[] args) {
args = new String[1];
args[0] = "--spring.profiles.active=zuul-simple";
SpringApplication.run(ZuulSimpleCloudApplication.class, args);
}
….
}
3.2.3. @EnableZuulProxy和@EnableZuulServer
有一个和@EnableZuulProxy很相似的@EnableZuulServer,这里说明这两个异同:@EnableZuulProxy包括@EnableZuulServer的所有功能,@EnableZuulServer是@EnableZuulProxy的功能子集。@EnableZuulProxy比@EnableZuulServer的多了代理的功能
3.2.4. 属性文件
bootstrap-zuul-simple.yml
bootstrap-zuul-simple.yml :配置服务注册到注册中心,服务名称为cloud-zuul
# port
server:
port: 14601
spring:
application:
# 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符
name: cloud-zuul
eureka:
client:
serviceUrl:
# 服务器注册/获取服务器的zone
defaultZone: http://127.0.0.1:10761/eureka/
instance:
prefer-ip-address: true
application-zuul-simple.yml
配置URL的路由关系,下节会详细介绍
3.3. 详细的Zuul路由配置
属性配置在application-zuul-simple.yml,本节对配置进行详细说明 路由配置以“zuul.routes.**”开头
3.3.1. 默认配置的路由
如果我们没有配置任何路由,则zuul默认已经自动配置类似的关系:
"/服务名称/**":"服务名称"
"/cloud-service-zuul/**":"cloud-service-zuul"
此时:访问
http://127.0.0.1:14601/cloud-service-zuul/zuul-test/simple
等价于
http://127.0.0.1:14606/zuul-test/simple
3.3.2. 设置忽略哪些服务
如果设置为*,则相当于关闭默认路由
zuul:
# 此参数设置忽略哪些服务,如果是*,则忽略所有服务
ignoredServices: '*
3.3.3. 通过url直接映射
Zuul的规则为:/api-a-url/**的访问都映射到
http://127.0.0.1:14606/
上
也就是说当我们访问
http://127.0.0.1:14601/api-a-url/zuul-test/simple
的时候,Zuul会将该请求路由到:
http://127.0.0.1:14606/zuul-test/simple
对于url映射不是通过HystrixCommand执行,也不能通过ribbon进行负载,需要进行额外配置,详细见spring 文档
zuul:
routes:
# 此名称任意
api-url:
# 所有到Zuul的中规则为:/api-a-url/**的访问都映射到http://127.0.0.1:14606/上,
# 也就是说当我们访问http://127.0.0.1:14601/api-a-url/zuul-test/simple的时候,Zuul会将该请求路由到:http://127.0.0.1:14606/zuul-test/simple
path: /api-a-url/**
# 对于url映射不是通过HystrixCommand执行,也不能通过ribbon进行负载,需要进行额外配置,详细见spring 文档
url: http://127.0.0.1:14606
3.3.4. 通过服务名进行映射关系
所有访问/api-a/开头的URL都会转到服务 cloud-service-zuul上
如访问
http://127.0.0.1:14601//api-a//zuul-test/simple
等价于
http://127.0.0.1:14606/zuul-test/simple