介绍
Zuul是Spring Cloud全家桶中的微服务API网关。所有从设备或网站来的请求都会经过Zuul到达后端的Netflix应用程序。作为一个边界性质的应用程序,Zuul提供了动态路由、监控、弹性负载和安全功能。Zuul底层利用各种filter实现如下功能:
1.认证和安全 识别每个需要认证的资源,拒绝不符合要求的请求。
2.性能监测 在服务边界追踪并统计数据,提供精确的生产视图。
3.动态路由 根据需要将请求动态路由到后端集群。
4.压力测试 逐渐增加对集群的流量以了解其性能。
5.负载卸载 预先为每种类型的请求分配容量,当请求超过容量时自动丢弃。
6.静态资源处理 直接在边界返回某些响应。
Spring-Cloud-Zuul 环境搭建的配置案例
案例中体现zuul的环境搭建,以及zuul的几种路由配置方式和本地跳转的配置
maven依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
应用启动类添加注解@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(ZuulApplication.class);
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
LOGGER.info("================ erueka start success ==============");
}
}
添加zuul的配置
zuul:
ignored-services: client-b #忽略的服务,防止服务侵入
ignored-patterns: /**/div/** #忽略的接口,防止侵入
prefix: /pre #路由前缀
add-host-header: false # 如果设置为true 解决重定向问题 比如未登录跳转到登录模块,但不能让客户发现zuul的存在
retryable: false #重试机制配合ribbon实现 默认关闭,要求下游接口支持幂等性 不建议开启
strip-prefix: true #是否移除代理的请求路径
routes:
server:
path: /server/** #http://127.0.0.1:8080/pre/server/hello/add
serviceId: server
sensitiveHeaders: Cookie, Set-Cookie,Authorization #敏感头信息不传递到下游服务
server1:
path: /server1/**
serviceId: http://127.0.0.1:8002 #http://127.0.0.1:8080/pre/server1/hello/add
server2:
path: /server2/**
serviceId: http://127.0.0.1:8002 #http://127.0.0.1:8080/pre/server2/hello/add
server3: #使用forword进行本地跳转
path: /client/** #路径的规则
url: forword:/client #跳转至 #http://127.0.0.1:8080/client
ribbon:
eager-load:
enabled: true #开启饥饿加载
本地跳转类
@RestController
public class HelloService {
@PostMapping("client")
public String add(@RequestBody String body) {
return body;
}
}