Spring Cloud Zuul
Spring Cloud Zuul 路由是微服务架构的不可或缺的一部分,提供动态路由、监控、弹性、安全等的边缘服务。Zuul 是 Netflix 出品的一个基于 JVM 路由和服务端的负载均衡器。
下面我们通过代码来了解 Zuul 是如何工作的
准备工作
在构建服务网关之前,我们先准备一下网关内部的微服务,可以直接使用前几篇编写的内容,比如:
eureka
producer
consumer
在启动了 eureka、producer 和 consumer 的实例之后,所有的准备工作就以就绪,下面我们来试试使用 Spring Cloud Zuul 来实现服务网关的功能。
首先创建一个基础的 Spring Boot 项目,命名为:api-gateway。
POM 配置
在 pom.xml 中引入以下依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
在配置文件 application.yml 中加入服务名、端口号、Eureka 注册中心的地址:
spring:
application:
name: api-gateway
server:
port: 14000
eureka:
client:
service-url:
defaultZone: http://localhost:7000/eureka/
启动类
使用 @EnableZuulProxy 注解开启 Zuul 的功能
@EnableZuulProxy
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
到这里,一个基于 Spring Cloud Zuul 服务网关就已经构建完毕。启动该应用,一个默认的服务网关就构建完毕了,同时能在 Eureka 里看到这个服务。
测试
由于 Spring Cloud Zuul 在整合了 Eureka 之后,具备默认的服务路由功能,即:当我们这里构建的 api-gateway 应用启动并注册到 Eureka 之后,服务网关会发现上面我们启动的两个服务 producer 和 consumer,欢迎大家加我qq:1038774626探讨技术问题。这时候 Zuul 就会创建两个路由规则。每个路由规则都包含两部分,一部分是外部请求的匹配规则,另一部分是路由的服务 ID。针对当前示例的情况,Zuul 会创建下面的两个路由规则:
转发到 producer 服务的请求规则为:/producer/**
转发到 consumer 服务的请求规则为:/consumer/**
最后,我们可以通过访问 14000 端口的服务网关来验证上述路由的正确性:
比如访问:http://localhost:14000/consumer/hello/windmt,该请求将最终被路由到 consumer 的 /hello 接口上。