Spring Cloud Zuul
服务网关是微服务架构中一个不可或缺的部分。
通过服务网关统一向外系统提供REST API的过程中,除了具备服务路由、均衡负载功能之外,它还具备了权限控制等功能。
Spring Cloud Netflix中的Zuul就担任了这样的一个角色,为微服务架构提供了前门保护的作用,同时将权限控制这些较重的非业务逻辑内容迁移到服务路由层面,使得服务集群主体能够具备更高的可复用性和可测试性。
Zuul功能:1.认证2.压力测试3.金丝雀测试4.动态路由5.负载削减6.安全7.静态响应处理8.主动/主动交换管理
Zuul的规则引擎允许通过任何JVM语言来编写规则和过滤器, 支持基于Java和Groovy的构建。
现在我们可以构建如下图的一个微服务架构:
微服务架构我们利用Eureka作为所有服务的统一的注册中心,利用Mysql存储的Config Service作为整个架构的配置文件存储。
负载均衡的控制,使用了Ribbo和Feign,还引入了熔断保护机制来防止系统的崩溃。
接下来我们就需要,对外面调用进行统一网关控制,这就需要使用到我们今天所要介绍的Zuul服务网关。
新建一个基础Spring的Maven Moudle工程命名为zuul,引用所需的依赖:
<parent>
<groupId>com.wkedong.springcloud</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
这里我们只依赖了配置中心和注册中心及zuul的依赖,后续拓展功能所需的功能可以自行添加。
配置文件bootstrap.yml
,如下:
eureka:
client:
healthcheck:
enabled: true #健康检查开启
serviceUrl:
defaultZone: http://localhost:6060/eureka/ #注册中心服务地址
server:
port: 6050 #当前服务端口
spring:
## 从配置中心读取文件
cloud:
config:
uri: http://localhost:6010/
label: master
profile: dev
name: zuul
application:
name: zuul #当前服务ID
配置文件中我们配置了
service-producer
的路由配置,Spring Cloud Zuul通过与Spring Cloud Eureka的整合,实现了对服务实例的自动化维护,具备默认的服务路由功能,即:当我们这里构建的zuul应用启动并注册到eureka之后,服务网关会发现上面我们启动服务,这时候Zuul就会创建两个路由规则。每个路由规则都包含两部分,一部分是外部请求的匹配规则,另一部分是路由的服务ID。
应用的主类
/**
* Zuul服务网关
*
* @author wkedong
*/
@EnableZuulProxy
@SpringCloudApplication
public class ZuulApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ZuulApplication.class).run(args);
}
}
在主类在加上注解
@EnableZuulProxy
开启Zuul的功能。
后续我们启动eureka,config,service-producer,zuul,并访问 http://localhost:6050/service-producer/testGet 会出现以下页面:
Hello, Spring Cloud! My port is 6070 Get info By Mybatis is {"address":"江苏南京","birthday":"1994-12-21","name":"wkedong"}
文章目录:
整体demo的GitHub地址:Spring-Cloud
网友评论