zuul 路由网关


Zuul

什么是Zuul?

  • Zuul包含了对请求的路由和过滤两个最主要的功能:

  • 其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础,而过滤器功能则负责对请求的处理进行干预,是实现请求效验,服务聚合等功能的基础。Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他微服务的消息,也让以后的访问微服务都是通过Zuul跳转后获得。

  • 注意: Zuul服务最终还是会注册到EUREKA

  • 提供: 代理+路由+过滤三大功能

使用

  • 添加一个新的子模块

1. 添加依赖

  • pom.xml

        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-ribbon
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
        
            cn.lzm
            springcloud-api
            1.0-SNAPSHOT
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-hystrix
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-hystrix-dashboard
        
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
    

2. 编写配置

  • application.yml
server:
  port: 9527
spring:
  application:
    name: springcloud-zuul

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:7001/eureka,http://127.0.0.1:7002/eureka,http://127.0.0.1:7003/eureka,
  instance:
    instance-id: zuul-9527
    prefer-ip-address: true

info:
  app.name: springcloud-zuul
  group.name: zuul

#zuul的配置
zuul:
  routes:
    person.serviceId: provider-person #服务名称
    person.path: /myperson/**   #别名对应的路径
  ignored-services: provider-person-8001 # 要忽略的服务名,即不能使用该名称访问了 * 表示所有服务都忽略
  prefix:  /cloud  # 添加一个统一的前缀,所有服务都要经过他才能访问
  • 主启动类
@SpringBootApplication
@EnableZuulProxy //zuul代理
public class Springcloud_Zuul {
    public static void main(String[] args) {
        SpringApplication.run(Springcloud_Zuul.class,args);
    }
}

访问

  • 在没有配置 zuul.rutes也能通过服务名去访问,如果服务(服务提供者)访问路径为 localhost:8001/person/get/1,根据上面的配置,可以通过 localhost:9527/服务名/person/get/1去访问

  • 只配置了zuul.rutes,既可以通过 localhost:9527/服务名/person/get/1 访问,也可以 通过 localhost:9527/myperson/person/get/1访问,如果还配置了zuul.ignored-services,就不能通过服务名去访问了

  • 如果配置了 zuul.prefix,则需要再加上前缀才能访问,如 localhost:9527/cloud/myperson/person/get/1