1. 程式人生 > >springcloud服務閘道器-gateway

springcloud服務閘道器-gateway

文件

Spring Cloud Gateway官方文件地址

特性

  • Java 8
  • Spring Framework 5
  • Spring Boot 2
  • 動態路由
  • 內建到Spring Handler對映中的路由匹配
  • 基於HTTP請求的路由匹配 (Path, Method, Header, Host, etc…​)
  • 過濾器作用於匹配的路由
  • 支援Spring Cloud DiscoveryClient配置路由,與服務發現與註冊配合使用

應用

本文springcloud基於Finchley.RELEASE版本

  1. pom.xml引入gateway依賴
        <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-netflix-hystrix</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
  1. 新建自定義filter,繼承AbstractGatewayFilterFactory
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 過濾器
 * @author 愛飄de小子
 */
@Slf4j
@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.Config> {

    public CustomGatewayFilterFactory() {
        super(Config.class);
        log.info("載入 自定義攔截器 [Custom]...");
    }

    @Override
    public Config newConfig() {
        return new Config();
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("enabled");
    }

    /**
     * @param config
     * @return
     */
    @Override
    public GatewayFilter apply(CustomGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {

            //Custom=false 跳過驗證
            if (!config.isEnabled()) {
                return chain.filter(exchange);
            }

            //獲取請求資訊
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders headers = request.getHeaders();

            //獲取請求引數  
            //具體業務略....
            String token = headers.getFirst("token");
            System.out.println("====token===="+token);
            return chain.filter(exchange);
        };
    }

    public static class Config {
        /**
         * 控制是否開啟攔截器
         */
        private boolean enabled;

        public Config() {}

        public boolean isEnabled() {
            return enabled;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }
}
  1. bootstrap.yml配置gateway
spring:
  application:
    name: gateway-demo

  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #是否開啟
          lower-case-service-id: true
      default-filters:  #全域性過濾器配置
      routes:
        - id: web
          uri: lb://epw-web
          predicates:
          - Path=/web/**
          filters:
            - StripPrefix=1
            # 配置自定義CustomGatewayFilterFactory  ,Custom是CustomGatewayFilterFactory的字首,gateway預設省略GatewayFilterFactory
            - Custom=true

        - id: common
          uri: lb://epw-common
          predicates:
            - Path=/common/**
          filters:
            - StripPrefix=1


eureka:
  instance:
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 10 #表示eureka client傳送心跳給server端的頻率,預設為30秒
    health-check-url-path: /actuator/health #健康檢查的地址(依賴spring-boot-starter-actuator)
  client:
    registry-fetch-interval-seconds: 10 #表示eureka client間隔多久去拉取服務註冊資訊,預設為30秒
    service-url:
      defaultZone: http://localhost:8761/eureka/

說明:

  • default-filters: 裡面可以定義一些共同的filter,對所有路由都起作用
  • routes:具體的路由資訊,是一個數組,每一個路由基本包含部分:
  • id:這個路由的唯一id,不定義的話為一個uuid
  • uri:http請求為lb://字首 + 服務id;ws請求為lb:ws://字首 + 服務id;表示將請求負載到哪一個服務上
  • predicates:表示這個路由的請求匹配規則,只有符合這個規則的請求才會走這個路由。為一個數組,每個規則為並且的關係。
  • filters:請求轉發前的filter,為一個數組。
  • order:這個路由的執行order

4.專案啟動啟動類

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;

/**
 * @author 愛飄de小子
 */
@SpringCloudApplication
public class GatewayApplication {

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

}

說明: @SpringCloudApplication是一個組合註解,包含@SpringBootApplication
@EnableDiscoveryClient