Spring Cloud构建微服务架构(二):路由网关(Zuul)
简单介绍了Spring Cloud,微服务的架构,如何解决服务治理中服务统一管理的问题,以及搭建基础的Spring Cloud的教程 。今天则主要介绍Spring Cloud的另一个服务治理组件——服务网关,或者说路由网关。
1. Zuul简介
2. Zuul工作原理 就像上图中所描述的一样,Zuul提供了四种过滤器的API,分别为前置(Pre)、后置(Post)、路由(Route)和错误(Error)四种处理方式。
四种过滤器的实际应用场景可参考 。
3. 动手配置路由网关
在上一个项目的基础上继续我们的路由网关配置。首先新建一个Spring boot项目,命名为api-geteway,并在pom.xml中引入需要的依赖内容:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
在应用启动类中通过加上@EnableZuulProxy开启网关代理功能,如下:
@SpringBootApplication @EnableEurekaClient @EnableZuulProxy public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } }
在配置文件中作如下配置:
spring.application.name=api-gateway server.port=9090 eureka.client.service-url.defaultZone=http://127.0.0.1:8761/eureka # 禁止服务自动添加 zuul.ignoredServices=* zuul.routes.api-a.path=/customer/** zuul.routes.api-a.serviceId=eureka-customer zuul.routes.api-b.path=/order/** zuul.routes.api-b.serviceId=eureka-order
我们启动api-gateway服务,将其注册到服务注册中心上,出现下图内容表示网关服务注册成功:
我们在eureka-customer中写一个服务进行测试,代码如下:
@RestController @RequestMapping(value = "/test") @Api(value = "测试", description = "测试模块", position = 1) public class TestController { @ApiOperation(value = "返回用户输入的结果", notes = "返回用户输入的结果") @RequestMapping(value = "/result", method = RequestMethod.GET) public String test(@RequestParam(value = "text") String text) { return text; } }
然后我们在游览器中输入 ,请注意,我们这里访问的是9090端口,而不是8200端口,实际执行结果:
到这里我们就已经发现Zuul的作用了,它可以将我们的请求分发到具体的服务上,而不是需要我们指定每一个服务的访问路径,当然这只是Zuul最基本的功能,但也是因为Zuul具备服务分发的功能,我们可以在服务分发之前进行权限校验,负载分配,可以对请求的结果进行洞察监测等等其他功能。
后面会陆续为大家介绍Zuul以及Zuul结合其他服务组件实现更多更强大的功能。项目地址:。