天天看點

Zuul Gateway 入門Zuul Gateway 入門

Zuul Gateway 入門

有點像 nginx 或者 servlet過濾器, 對外隐藏微服務的域名和端口,隻需要知道 微服務名字和 uri 即刻通路指定 微服務,友善統一管理

Pom

<dependencies>
        <!--Zuul 網關-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>

        <!--Eureka用戶端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
           

Main

/**
 * @author ratel
 * @date 2020/4/5
 */
@EnableZuulProxy //标記此應用為 Zuul Gateway
@EnableDiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class,args);
    }
}
           

Config

spring:
  application:
    name: @artifactId@
server:
  port: 8070
#  servlet:
#    context-path: /zuul

# eureka 注冊中心配置
eureka:
  instance:
    prefer-ip-address: true
  client:
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka1.ratel.com:8001/eureka/

# 指定路由規則
zuul:
  routes:
#    api-a:
#      path: /order/** #比對路徑
#      serviceId: ratel-microservice-order #微服務名字
#      url: http://localhost:8082 #重定向,不依賴 eureka
#簡寫
    ratel-microservice-order: #微服務名字
      path: /order/** #比對規則
#  ignored-services: ratel-microservice-order #忽略掉這個微服務,否則url以 /ratel-microservice-order 為字首的也會通路 order 服務
logging:
  level:
    root: debug

           

進階配置

請求轉發

# 指定路由規則
# 比對優先級 按配置先後循序
zuul:
  routes:
    api-foward: #微服務名字 或 url 字首
      path: forward:/test #表示将比對上的 請求轉發到目前網關的接口上
           

Example

  • 不使用網關
    Zuul Gateway 入門Zuul Gateway 入門
  • 使用Zuul網關

    [外鍊圖檔轉存失敗,源站可能有防盜鍊機制,建議将圖檔儲存下來直接上傳(img-XQGine4l-1586100144062)(/Users/ratel/Library/Application Support/typora-user-images/image-20200405231532598.png)]