前言:本章将继续上一章Spring Cloud微服务,本章主要内容是API 网关,相关代码将延续上一章,如需了解请参考:Spring Cloud 微服务一:Consul注册中心
- Spring cloud zuul概览 zuul 是netflix开源的一个API Gateway 服务器, 本质上是一个web servlet应用。Zuul 在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。Spring对zuul进行了整合,使开发者能够很方便地使用zuul
- 集成zuul
- 延续上一个项目,新建module api-gateway pom中添加zuul的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency>
- 在启动类中添加@EnableZuulProxy注解,启用zuul
@SpringBootApplication @EnableZuulProxy public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }
- 修改配置文件application.yml,设置相关路由,url为上一章中consul消费者的地址
server: port: 8080 spring: application: name: api-gateway zuul: routes: user: path: /user/** url: http://localhost:10080/ debug: true
- 分别启动user-service,user-consumer,api-gateway,访问 http://localhost:8080/user/users, 能够正常返回信息,说明路由已成功
- 延续上一个项目,新建module api-gateway pom中添加zuul的依赖