#### API 网关服务-Zuul
- 场景举例
> 假设你后台部署了几百个服务,现在前端从浏览器直接发出请求,打个比方:请求一下库存服务,难道还让前端记着这服务的名字叫做xxxx-service?部署在好几台台机器上,不同的端口,就算前端记住这一个,你后台可有几百个服务的名称和地址呢?所以网关Zuul应运而生
- 所有请求统一从网关进入,如下图所示
![](https://box.kancloud.cn/9408d4d8431b799c191f4079b338240d_665x458.png)
- 引入依赖
```
<!-- 服务网关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
```
- application.yml serviceId-服务名称唯一
```
spring:
application:
name: sc-zuul
eureka:
client:
serviceUrl:
defaultZone: http://192.168.0.114:8001/eureka/,http://192.168.0.114:8002/eureka/,http://192.168.0.114:8003/eureka/
zuul:
routes:
api-a:
path: /api-data/**
serviceId: sc-eureka-client
api-b:
path: /api-view/**
serviceId: sc-feign
server:
port: 9999
```
- 启动类
```
package com.dg.sc.zuul;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
/**
* 〈服务网关〉
*
* @author xieth
* @create 2019/6/11
* @since 1.0.0
*/
@SpringCloudApplication
@EnableZuulProxy //服务网关
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run( ZuulApplication.class,args );
}
}
```
- 注册中心界面可以看到Zuul服务已经注册成功
![](https://box.kancloud.cn/a91fc93cef680deba19923a7c9abd75a_1050x215.png)
- 运行,浏览器输入 [http://localhost:9999/api-view/products](http://localhost:9999/api-view/products)
![](https://box.kancloud.cn/b647c74b3f4e39ef2729a6cc445e2174_950x225.png)
- http://localhost:9999/api-view/products 等价于 http://localhost:4444/products