在微服务架构中,通常会有多个服务提供者。设想一个电商系统,可能会有商品、订单、支付、用户等多个类型的服务,而每个类型的服务数量也会随着整个系统体量的增大也会随之增长和变更。作为UI端,在展示页面时可能需要从多个微服务中聚合数据,而且服务的划分位置结构可能会有所改变。网关就可以对外暴露聚合API,屏蔽内部微服务的微小变动,保持整个系统的稳定性。
Zuul在微服务网关中是非常容易使用的。(题外话,Zuul在springboot中简单使用就是一行注解,但在实际情况使用主要是限流的作用,或者网段不信任才会使用网关)
这些是我本文所用的例子。(按此顺序开启)
https://github.com/lihang212010/demo-cloud-Eureka
https://github.com/lihang212010/demo-cloud-user
https://github.com/lihang212010/demo-cloud-consume
https://github.com/lihang212010/demo-cloud-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>
在启动类上加注解@EnableZuulProxy
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@SpringBootApplication
public class DemoCloudZuulApplication {
public static void main(String[] args) {
SpringApplication.run(DemoCloudZuulApplication.class, args);
}
}
修改配置文件
server:
port: 8040
spring:
application:
name: demo-cloud-zuul
eureka: #注册如Eureka
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
management:
securtty:
enabled: false
endpoints: #开放所有端口
web:
exposure:
include: "*"
就这样一个微服务网管就写好了,默认情况下,他会代理所以的Eureka Server微服务。
接下来讲下它的2个重要端点
routes
http://localhost:8040/actuator/routes
2.0以上版本使用此种方法,这个端口反映当前的路由映射表,我的上面只有2个微服务。
filters
http://localhost:8040/actuator/filters
了解error,post,pre,route过滤器类型以及执行顺序
(1) PRE:这种过滤器在请求被路由之前调用。可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。
(2) ROUTING:这种过滤器将请求路由到微服务。这种过滤器用于构建发送给微服务的请求,并使用Apache HttpClient或Netfilx Ribbon请求微服务。
(3) POST:这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。
(4) ERROR:在其他阶段发生错误时执行该过滤器。