这篇文章将为大家详细讲解有关春云如何使用Zuul实现API网关服务问题,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
通过前面几次的分享,我们了解了微服务架构的几个核心设施,通过这些组件我们可以搭建简单的微服务架构系统。比如通过春云尤里卡搭建高可用的服务注册中心并实现服务的注册和发现,
通过春云带或装进行负载均衡;通过春云Hystrix进行服务容错保护以避免故障蔓延。微服务搭建好了之后我们肯定会提供给外部系统一些统一的RESTFul API服务接口进行调用,
但是当外部系统调用我们的RESTFul API的时候,怎么确定它需要的功能具体是哪个服务提供的呢?这个就涉及到一个路由规则和服务实例列表的维护问题。
这就引入了我们今天的主云Zuul角——春天,它是基于Netflix Zuul实现的API网关组件。它可以解决两个大问题:
- <李>
就是我们上面提到的路由规则和服务实例的维护问题
对于一些校验(比如登录校验等)冗余问题。按照我们的习惯的做法,是在每个服务中都需要加入这些校验,但是这样会导致代码冗余并且维护也比较麻烦,有了春天的云Zuul这个网关服务之后,我们可以将这些共通的校验放到网关里面统一维护。
好,接下来我们就来看下怎么实现这个网关服务。
<强>一、构建网关,配置路由强>
,这里我们还是需要使用到前面的hello-service和feign-consumer服务。我们之前把feign-consumer作为服务消费者,但是别忘了在尤里卡体系里面,每个服务既是服务提供者又是服务消费者,所以feign-consumer也是一个服务提供者,并且http://localhost: 9001/feign-consumer等接口就是它提供的服务。
接下来我们构建一个网关服务,代码结构如下:
代码实现步骤:
新建maven工程API网关
修改POM文件
& lt; project xmlns=癶ttp://maven.apache.org/POM/4.0.0", xmlns: xsi=癶ttp://www.w3.org/2001/XMLSchema-instance", xsi: schemaLocation=? http://maven.apache.org/POM/4.0.0 , http://maven.apache.org/xsd/maven-4.0.0.xsd"比; ,& lt; modelVersion> 4.0.0 ,& lt; groupId> com.sam ,& lt; artifactId> api-gateway ,& lt; version> 0.0.1-SNAPSHOT ,& lt; parent> & lt;才能groupId> org.springframework.boot</groupId> & lt;才能artifactId> spring-boot-starter-parent</artifactId> & lt;才能version> 1.5.1.RELEASE</version> ,& lt;/parent> ,& lt; properties> & lt;才能javaVersion> 1.8 & lt;/javaVersion> ,& lt;/properties> ,& lt; !——,使用dependencyManagement进行版本管理,——比; ,& lt; dependencyManagement> & lt;才能dependencies> ,,& lt; dependency> ,,,& lt; groupId> org.springframework.cloud ,,,& lt; artifactId> spring-cloud-dependencies ,,,& lt; version> Camden.SR6 ,,,& lt; type> pom ,,,& lt; scope> import ,,& lt;/dependency> & lt;才能/dependencies> ,& lt;/dependencyManagement> ,& lt; dependencies> & lt; !——,才能引入zuul依赖,,,它依赖了spring-boot-starter-actuator/spring-boot-starter-hystrix spring-boot-starter-ribbon——比; & lt;才能dependency> ,,& lt; groupId> org.springframework.cloud ,,& lt; artifactId> spring-cloud-starter-zuul & lt;才能/dependency> ,& lt;/dependencies> & lt;/project>
新建启动类
/* * ,* @EnableZuulProxy 开启Zuul 的API网关服务功能 ,* ,*/@EnableZuulProxy @SpringCloudApplication public class  GateWayApp { ,public static  void main (String [], args), { SpringApplication.run才能(GateWayApp.class, args); ,} }
新建应用程序。属性
server.port=5555 spring.application.name=api网关 #增加路由规则的配置 #通过zuul.routes灵活;route> .path和zuul.routes灵活;route> .url进行配置,& lt; route>为路由的名字,可以任意指定,但是一组路径和url的路由名要相同 #如下面的例子:所有满足/api/* *,规则的访问都会被路由转发到//localhost: 9001年的地址 #也就是说,我们访问http://localhost: 5555/API/hello的时候,API网关服务就会将该请#求路由到,http://localhost: 9001/你好提供的微服务接口上 zuul.routes.api-a.path=/api/* * zuul.routes.api-a.url=http://localhost: 9001 zuul.routes.api-b.path=/api-b/* * zuul.routes.api-b。url=http://localhost: 9090春云如何使用Zuul实现API网关服务问题