8.Gateway

1.创建工程
1.1 加入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.43</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.6.0</version>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.8.13</version>
</dependency>

2.代码
2.1 配置RouteLocatorBuilder

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    //@formatter:off
    return builder.routes()
            .route("path_route", r -> r.path("/get")
                    .uri("http://httpbin.org"))
            .route("testfilter", r -> r.path("/testfilter/**").filters(f -> f.prefixPath("").filter(new GatewayCheckFilter()))
                    .uri("lb://service-a/test"))
            .route("path_getConf", r -> r.path("/getConf")
                    .uri("lb://service-a/getConf"))
            .route("path_actuator", r -> r.path("/actuator")
                    .uri("lb://service-a/actuator"))
            .route("host_route", r -> r.host("*.myhost.org")
                    .uri("http://httpbin.org"))
            .route("rewrite_route", r -> r.host("*.rewrite.org")
                    .filters(f -> f.rewritePath("/foo/(?<segment>.*)",
                            "/${segment}"))
                    .uri("http://httpbin.org"))
            .route("hystrix_route", r -> r.host("*.hystrix.org")
                    .filters(f -> f.hystrix(c -> c.setName("slowcmd")))
                    .uri("http://httpbin.org"))
            .route("hystrix_fallback_route", r -> r.host("*.hystrixfallback.org")
                    .filters(f -> f.hystrix(c -> c.setName("slowcmd").setFallbackUri("forward:/hystrixfallback")))
                    .uri("http://httpbin.org"))
            .route("limit_route", r -> r
                    .host("*.limited.org").and().path("/anything/**")
                    .filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter())))
                    .uri("http://httpbin.org"))
            .route("websocket_route", r -> r.path("/echo")
                    .uri("ws://localhost:9000"))
            .build();
}

2.2 根据需要配置
GatewayFilter和GlobalFilter

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    //获取path
    RequestPath allPath = request.getPath();
    String path = allPath.pathWithinApplication().value();
    //不拦截资源文件
    for (String url : excludedUrls) {
        if (path.contains(url)) {
            return chain.filter(exchange);
        }
    }
    staffService = exchange.getApplicationContext().getBean(StaffService.class);

    //获取参数
    String userName = request.getQueryParams().getFirst("userName");
    String pwd = request.getQueryParams().getFirst("pwd");

    //获取response
    ServerHttpResponse response = exchange.getResponse();
    response.setStatusCode(HttpStatus.OK);
    //设置headers
    HttpHeaders httpHeaders = response.getHeaders();
    httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
    httpHeaders.add("X-Content-Type-Options", "");

    if (!"abc".equals(userName) || !"123".equals(pwd)) {
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap("gateway wrong".getBytes());
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
    return chain.filter(exchange);
}

3.配置文件

spring:
  application:
    name: gateway
# 过滤器/转发配置 begin--------------------------------------
  cloud:
    gateway:
      default-filters:
      routes:
      #------------------------------------------------------------------------
      - id: modulea
        uri: lb://service-a
        predicates:
        - Path= /ma/**
        filters: # 调用目标工程时 省略ma路径 根据项目需要配置
        - StripPrefix= 1
      #------------------------------------------------------------------------
      - id: moduleb
        uri: lb://service-b
        predicates:
        - Path= /mb/**
        filters:
        - StripPrefix= 1

推荐阅读更多精彩内容