@Spring Cloud | NO.3 - 路由器和過濾器 Zuul

什麼是Zuul

路由是微服務體系結構的一個組成部分。例如,/能夠映射到您的Web應用程序,/api/users映射到用戶服務,並將/api/shop映射到商店服務。Zuul是Netflix的基於JVM的路由器和服務器端負載均衡器。html

Netflix使用Zuul進行如下操做:java

  • 認證
  • 洞察
  • 壓力測試
  • 金絲雀測試
  • 動態路由
  • 服務遷移
  • 負載脫落
  • 安全
  • 靜態響應處理
  • 主動/主動流量管理

Zuul的規則引擎容許基本上寫任何JVM語言編寫規則和過濾器,內置Java和Groovy。web

以上內容官方直譯

項目集成之Zuul

1. pom.xml引入Maven依賴

<parent>
    <!-- spring boot -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <!-- netflix-eureka-client-->
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <!-- netflix-zuul -->
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <!-- spring cloud -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley RC1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
注意: Zuul引入的Maven依賴中 artifactId有變更, SpringBoot2.0以前的版本爲 spring-cloud-starter-zuul

2. 添加註解支持

@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class ZuulServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }
}

3. application.yml配置

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-ribbon
    api-b:
      path: /api-b/**
      serviceId: service-feign
將名稱爲 service-zuulZuul服務註冊到註冊中心,端口爲 8769
配置路由相關參數,將 path屬性值對應的地址 轉發給服務名稱爲 serviceId屬性值的服務

4. 運行概覽圖

啓動一個服務註冊中心,兩個服務提供者,一個服務消費者(Ribbon),一個服務消費者(Feign),一個Zuul路由服務

服務註冊中心

訪問 http://localhost:8769/api-a/h...,瀏覽器顯示:spring

hi forezp,i am from port:8762

訪問 http://localhost:8769/api-b/h...,瀏覽器顯示:api

hi forezp,i am from port:8762

附加說明

  1. 本文參考資料
相關文章
相關標籤/搜索