天天看點

zuul網關_服務網關Zuul和SpringCloudGateway

zuul網關_服務網關Zuul和SpringCloudGateway

本文參考了<Spring Cloud微服務和分布式系統實戰>一書, 表示感謝!

具體可關注公衆号: 戲說碼農職場

首先二者都是服務網管, Zuul是舊的API網關, 後者是新的, 先比較下二者差別:

  1. Zuul 來自Netflix, 提供身份驗證, 安全校驗, 限流, 動态路由等, 但是性能一般
  2. Gateway是在Zuul基礎之上建立.

基本定義:

  • 網關: 是一種外部網絡和内部網絡的關卡, 通過網關進行轉發, 可以分為硬體網關和軟體網關, 硬體網關包括LVS 和F5, 軟體網關包括Nginx,Zuul, Gateway等, 主要作用展現在請求過濾和路由轉發功能.

簡單介紹下使用

Zuul

  1. 如何使用

增加依賴

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
           

入口方法

@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class ZuulProxyApplication {

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

}
           

可以看出Zuul定義為一個服務代理的角色. 繼續稍微看下源碼:

@EnableCircuitBreaker
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ZuulProxyMarkerConfiguration.class)
public @interface EnableZuulProxy {

}
           

其中@EnableCircuitBreaker 表面内部是是要斷路器Hystrix.

# 定義Spring應用名稱,它是一個微服務的名稱,一個微服務可擁有多個執行個體
spring:
 application:
  name: zuul

# 向端口為5001和5002的Eureka服務治理中心注冊
eureka:
 client:
  serviceUrl:
   defaultZone: http://localhost:5001/eureka, http://localhost:5002/eureka

# Zuul的配置
zuul:
 # 路由配置
 routes:
  # 使用者微服務
  user-service:
    # 請求攔截路徑配置(使用ANT風格)
    path: /u/**
    # 通過一個URL配置
    url: http://localhost:6001/
  # 産品微服務配置
  fund-service:
    # 請求攔截路徑配置(使用ANT風格)
    path: /p/**
    service-id: product
           

意味着/u/user/info/1會被映射為localhost:6001/user/info/1

以上是攔截器的功能

2. 限流

依賴springCloud Resilience4j限速器, rateLimiter

那又如何限制呢?

# resilience4j配置
resilience4j:
 # 限速器注冊機
 ratelimiter:
  limiters:
   # 名稱為“user”的限速器
   user:
     # 時間戳内限制通過的請求數,預設為50
    limitForPeriod: 3
    # 配置時間戳(機關毫秒),預設值為500 ns
    limitRefreshPeriodInMillis: 5000
    # 逾時時間
    timeoutInMillis: 10
           

3. 動态路由

可以使用MySQL儲存服務資訊

4. 網關過濾

SpringCloudGateway

特點:

  1. Spring Cloud Gateway 底層使用了高性能的通信架構Netty

2. 三個術語: 過濾, 路由和斷言

詳細說明轉自:

SpringCloud gateway (史上最全)

繼續閱讀