Zuul
什么是Zuul
Zuul是Spring Cloud全家桶中的微服务API网关。
所有从设备或网站来的请求都会经过Zuul到达后端的Netflix应用程序。作为一个边界性质的应用程序,Zuul提供了动态路由、监控、弹性负载和安全功能。Zuul底层利用各种filter实现如下功能:
- 认证和安全 识别每个需要认证的资源,拒绝不符合要求的请求。
- 性能监测 在服务边界追踪并统计数据,提供精确的生产视图。
- 动态路由 根据需要将请求动态路由到后端集群。
- 压力测试 逐渐增加对集群的流量以了解其性能。
- 负载卸载 预先为每种类型的请求分配容量,当请求超过容量时自动丢弃。
- 静态资源处理 直接在边界返回某些响应。
编写一个Zuul网关
依赖
在依赖项处添加【Cloud Discovery->Eureka client和Cloud Rouing->Zuul】。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
spring:
application:
name: springcloud-zuul
eureka:
client:
service-url:
defaultZone: http://localhost:6998/eureka/,http://localhost:6999/eureka/,http://localhost:7000/eureka/
instance:
instance-id: zuul9999.com
prefer-ip-address: true
zuul:
routes: #设置路由。这里是一个key-values,可以设置多个,名字可自定义
mydept.serviceId: springcloudeprovides # 我们的服务名称
mydept.path: /mydept/** # 服务名称被替换后的名字
ignored-services: "*" # 不能再使用这个路径访问了,ignored : 忽略,隐藏全部的~
server:
port: 9999
主启动类
@SpringBootApplication
@EnableZuulProxy
public class SpringcloudZuul9999Application {
public static void main(String[] args) {
SpringApplication.run(SpringcloudZuul9999Application.class, args);
}
}
启动的模块
一个eureka服务端、一个服务提供者、一个zuul.
可以看到我们访问zuul的服务器是可以访问我们的服务提供者的。
路由配置
Zuul提供了一套简单且强大路由配置策略,利用路由配置我们可以完成对微服务和URL更精确的控制。
1、重写指定微服务的访问路径:
zuul:
routes:
rest-demo: /rest/**
这表示将rest-demo微服务的地址映射到/rest/**路径。
2、忽略指定微服务:
zuul:
ignored-services: rest-demo,xxx-service
使用“*”可忽略所有微服务,多个指定微服务以半角逗号分隔。
3、忽略所有微服务,只路由指定微服务:
zuul:
ignored-services: *
routes:
rest-demo: /rest/**
4、路由别名:
zuul:
routes:
route-name: #路由别名,无其他意义,与例1效果一致
service-id: rest-demo
path: /rest/**
5、指定path和URL
zuul:
routes:
route-name:
url: http://localhost:8000/
path: /rest/**
此例将http://ZUULHOST:ZUULPORT/rest/映射到http://localhost:8000/。同时由于并非用service-id定位服务,所以也无法使用负载均衡功能。
6、即指定path和URL,又保留Zuul的Hystrix、Ribbon特性
zuul:
routes:
route-name: #路由别名,无其他意义,与例1效果一致
service-id: rest-demo
path: /rest/**
ribbon:
eureka:
enable: false #为Ribbon禁用Eureka
rest-demo:
ribbon:
listOfServers: localhost:9000,localhost:9001