SpringCloud Zuul(路由网关)
⒈Zuul是什么?
Zuul包含了两个最主要的功能,对请求的路由和过滤。其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础。过滤器功能则负责对请求的处理过程进行干预,是实现请求校验、服务聚合等动能的基础。
Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其它微服务的消息,也就是说,以后访问微服务都是通过Zuul跳转后获得。Zuul服务最终还是会注册进Eureka。
⒉示例
①新建路由项目,添加依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-web</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.springframework.cloud</groupId> 7 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 8 </dependency> 9 <dependency> 10 <groupId>org.springframework.cloud</groupId> 11 <artifactId>spring-cloud-starter-netflix-zuul</artifactId> 12 </dependency>
②配置文件(yml)
1 spring: 2 application: 3 name: user-zuul 4 eureka: 5 instance: 6 prefer-ip-address: true #主机ip是否显示 7 client: 8 service-url: 9 defaultZone: http://localhost:8761/eureka/
③主程序启动类添加@EnableZuulProxy注解
1 package cn.coreqi; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.cloud.netflix.zuul.EnableZuulProxy; 6 7 @SpringBootApplication 8 @EnableZuulProxy 9 public class SpringbootcloudzuulApplication { 10 11 public static void main(String[] args) { 12 SpringApplication.run(SpringbootcloudzuulApplication.class, args); 13 } 14 15 }
④访问http://localhost:9527/user-provider/users http://localhost:9527:网关 user-provider:微服务名称 users:调用
⑤★配置文件高级设置
1 server: 2 port: 9527 3 spring: 4 application: 5 name: user-zuul 6 eureka: 7 instance: 8 prefer-ip-address: true #主机ip是否显示 9 client: 10 service-url: 11 defaultZone: http://localhost:8761/eureka/ 12 zuul: 13 ignored-services: "*" #禁用所有真实微服务地址访问 14 #ignored-services: user-provider #禁用单个的真实微服务地址访问 15 prefix: /coreqi #统一访问公共前缀 16 routes: 17 user.serviceId: user-provider 18 user.path: /test/** #微服务域名映射
⑥访问http://localhost:9527/coreqi/test/users