Spring Cloud 學習 - Gateway新一代網關

Spring Cloud Gateway 新一代網關

Spring Cloud Gateway 是Spring Cloud的一個全新項目,基於Spring 5.0 + Spring Boot 2.x和Project Reactor等技術開發的網關,旨在爲微服務架構提供一種有效的統一的API路由管理方式。

Spring Cloud Gateway作爲Spring Cloud生態系統中的網關組件,目標是替代Zuul。由於Zuul2.x的多次跳票,爲了提升網關的性能,Spring Cloud官方基於Spring WebFlux開發了非阻塞的網關組件Gateway,WebFlux框架底層使用了高性能的Reactor模式的非阻塞通信框架Netty。

引入依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

因爲要從註冊中心對服務實例進行動態路由,這裏加入了eureka-client的依賴,把gateway註冊到eureka中。

服務發現

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

編寫配置

事前先編寫如下2個服務,並提供相應的接口,服務名稱分別爲cloud-providercloud-consumer
在這裏插入圖片描述
在這裏插入圖片描述

server:
  port: 8008
spring:
  application:
    name: cloud-gateway
  devtools:
    livereload:
      port: 35731 # 設置熱部署插件端口,防止端口衝突導致熱加載不生效
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 開啓動態路由,不配置uri時默認訪問路徑:/serviceId/url, e.g. http://localhost:8008/cloud-provider/provider/xudc
          lower-case-service-id: true # 啓用serviceId小寫功能,默認是全部大寫,e.g. CLOUD-PROVIDER,開啓後:cloud-provider
      routes:
        - id: spring-cloud-provider # 指定路由id,可任意名稱,唯一即可
          uri: lb://cloud-provider # lb表示負載均衡到<serviceId>
          predicates:
            - Path=/provider/**

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

自定義全局過濾

@Component
public class CustomFilter implements GlobalFilter, Ordered {
    /**
     * 模擬用戶登錄過濾
     * 攜帶token參數則認爲是授權的,未攜帶則未授權,拒絕訪問
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getQueryParams().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] bytes = "{\"status\": 401,\"message\": \"Unauthorized Request!請求未授權\"}".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            // 設置編碼utf-8,否則瀏覽器中文可能會亂碼
            response.getHeaders().add("content-type", "text/plain;charset=utf-8");
            // return exchange.getResponse().setComplete();
            return response.writeWith(Flux.just(buffer));
        }
        // 通過則放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

測試

GET http://localhost:8008/provider/cindy

HTTP/1.1 401 Unauthorized
transfer-encoding: chunked
content-type: text/plain;charset=utf-8

{"status": 401,"message": "Unauthorized Request!請求未授權"}
GET http://localhost:8008/provider/cindy?token=qwerasd

HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 12

Hello, cindy

以上就是Spring Cloud Gateway的簡單使用。
更多功能使用,請參閱官方文檔: https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html/#gateway-starter

因個人能力有限,如果不足或錯誤之處,歡迎指正~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章