SpringCloud学习笔记(4)——Zuul
参考Spring Cloud官方文档第19章
19.Router and Filter: Zuul
路由是微服务架构的一部分。例如,"/"可能映射到你的web应用,"/api/users"可能映射到你的user服务,"/api/shop"可能映射到你的shop服务。Zuul是一个基于JVM的路由器和服务端的负载均衡器。

Zuul的规则引擎可以用任何JVM语言来写,内置的支持Java和Groovy。
注意:配置属性zuul.max.host.connections已经被两个新的属性所替代,zuul.host.maxTotalConnections和zuul.host.maxPerRouteConnections,它们的默认值分别是200和20。
19.1How to Include Zuul

19.2Embedded Zuul Reverse Proxy
Spring Cloud已经创建了一个内嵌的Zuul代理来方便进行通用的开发,它通常的使用场景是一个UI应用想要代理一个或者多个后端服务的调用。
为了使用它,需要在Spring Boot的运行主类上加@EnableZuulProxy注解,这样它就可以转发本地调用给合适的服务。按照惯例,一个ID叫做"users"的服务,将会从proxy那里收到定位到/users的请求。Proxy使用Ribbon来定位一个实例进而转发,并且所有的请求都加上了断路器,一旦断路器打开,proxy将不再尝试连接这个服务。
为了跳过一些服务,可以设置zuul.ignored-services。如果一个服务既匹配忽略规则,又明确的包含在路由映射中,那么它将不被忽略。例如

为了更好的控制路由,你可以指定服务ID和路径,例如:

另一种方式是配合Ribbon来实现多个实例的路由访问

19.15.3 @EnableZuulProxy
VS @EnableZuulServer
Spring Cloud Netflix基于开启Zuul的注解提供了大量的过滤器。@EnableZuulProxy包含所有安装在@EnableZuulServer中的注解,如果你想使用空的Zuul,请使用@EnableZuulServer


一言不合就上代码
这次新建两个服务提供方,一个叫user-service,另一个叫order-service。至于配置和pom都和以前一样,主要是引入eureka-client,然后配置端口之类的。

然后,再建一个工程zuul-demo。这个工程没啥特别的,并没有做特殊的配置,没有做路由配置,但是仍然具有路由功能。



启动这4个工程,如图

接下来就可以访问了


可以看到,主机是localhost:8090,这是zuul-demo这个工程,也就是我们通过zuul-demo可以访问到order-service和user-service上的服务,这就是网关的作用。
有一点很重要,网关是对外的。而且,应该注意到,这里我们并没有配置任何路由规则,但是仍然可以正确的路由,这一切得归功于Eureka,如果没有注册中心的话又想路由的话就得配路由规则了。不过,保险起见,还是明确指定路由规则吧。
接下来配个规则


过滤器
19.15.7How to Write a Pre Filter



参考
http://blog.didispace.com/spring-cloud-starter-dalston-6-2/
http://blog.didispace.com/spring-cloud-starter-dalston-6-3/