Tip: 此篇已加入. NET Core 微服务基础系列文章索引, 本篇接上一篇《基于 Steeltoe 使用 Eureka 实现服务注册与发现》, 所演示的示例也是基于上一篇的基础上而扩展的.
一, 关于 Spring Cloud Zuul
API Gateway(API GW / API 网关), 顾名思义, 是出现在系统边界上的一个面向 API 的, 串行集中式的强管控服务, 这里的边界是企业 IT 系统的边界.
Zuul 是 Netflix 提供的一个开源组件, 致力于在云平台上提供动态路由, 监控, 弹性, 安全等边缘服务的框架, 也有很多公司使用它来作为网关的重要组成部分. Spring Cloud 体系收录的该模块, 主要用于提供动态路由, 监控, 安全控制, 限流配额等, 可以将内部微服务 API 同意暴露.
有关 Zuul 的更多内容, 请参考我的这一篇:《Spring Cloud 微服务架构学习笔记与示例》, 这里不是本文重点, 不再赘述.
二, 快速构建 Zuul Server
(1)pom.xml 添加相关依赖包: 本示例的版本 => Spring Boot 1.5.15.RELEASE,Spring Cloud Edgware.SR3
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <!-- zuul -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-zuul</artifactId>
- </dependency>
- <!-- eureka -->
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-eureka</artifactId>
- </dependency>
- <!-- 热启动, 热部署依赖包, 为了调试方便, 加入此包 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <optional>true</optional>
- </dependency>
- </dependencies>
- <!-- spring cloud dependencies -->
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-dependencies</artifactId>
- <version>Edgware.SR3</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
(2) 启动类添加 @EnableZuulProxy 注解
- @SpringBootApplication
- @EnableZuulProxy
- public class ZuulServiceApplication {
- public static void main(String[] args) {
- SpringApplication.run(ZuulServiceApplication.class, args);
- }
- }
(3) 添加必要配置 (application.YAML): 主要是针对 Eureka 的配置, 本示例将 Zuul 也作为一个 Eureka Client 注册到 Eureka Server 中.
- server:
- port: 5000
- spring:
- application:
- name: zuul-gateway-service
- eureka:
- client:
- serviceUrl:
- defaultZone: http://localhost:8761/eureka/
- instance:
- prefer-ip-address: true # 优先注册 IP 地址而不是 hostname
- instance-id: zuul-gateway-container:${server.port}
- healthcheck:
- enabled: true # 启用健康检查, 注意: 需要引用 spring boot actuator
- management:
- security:
- enabled: false # 默认为 true, 改为 false 以便可以看到 routes
启动 Eureka Server 和 Zuul Server 之后:
示例代码: https://GitHub.com/EdisonChou/Microservice.PoC.Steeltoe/tree/master/springcloud/zuul-service
三, 快速验证测试
基于第一篇的三个已注册到 Eureka 的 ASP.NET Core webAPI 示例项目 (示例代码:), 无须做任何修改, 启动并注册到 Eureka 之后的服务列表:
(1) 通过 Zuul 访问 Agent-Service
(2) 通过 Zuul 访问 Premium-Service
(3) 通过 Zuul 访问 Client-Service (多 Client-Service 实例, 验证负载均衡)
四, 小结
本文极简地介绍了一下 Spring Cloud Zuul, 并使用 Java 快速地编写了一个 API 网关 Zuul Server, 然后基于上一篇的三个 ASP.NET Core 演示了一下 API 网关的效果. 当然, 对于 Zuul 还有很多内容, 这里就不再一一演示, 有兴趣的童鞋或者对这种混搭式的架构感兴趣的童鞋可以去了解一下.
来源: https://www.cnblogs.com/edisonchou/p/dotnet_core_microservice_integrate_with_springcloud_zuul.html