背景

gateway版本:2.2.6.RELEASE GA

一、介绍

Spring生态系统之上构建的API网关,包括:Spring 5,Spring Boot 2和Project Reactor。
Spring Cloud Gateway旨在提供一种简单而有效的方法来路由到API,并为它们提供跨领域的关注点,例如:安全性,监视/指标和弹性。
基于Webflux框架实现的,而Webflux框架底层则使用了高性能的Reactor模式通信框架Netty。

注意:在没有端口的路由中定义的URI,HTTP和HTTPS URI的默认端口值分别为80和443。

工作原理图:
Spring Cloud Gateway - 图1

客户端向Spring Cloud Gateway发出请求。如果网关处理程序映射确定请求与路由匹配,则将其发送到网关Web处理程序。该处理程序通过特定于请求的过滤器链运行请求。筛选器由虚线分隔的原因是,筛选器可以在发送代理请求之前和之后运行逻辑。所有“前置”过滤器逻辑均被执行。然后发出代理请求。发出代理请求后,将运行“后”过滤器逻辑。

二、pom配置

  1. <!--gateway自带了spring-boot-starter-web/actuator-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-gateway</artifactId>
  5. </dependency>

三、全局网关日志配置

package com.its.cloud.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author huguangjun
 * @className GatewayFilter
 * @date 2021/1/11
 * @desc 19:18
 */
@Slf4j
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    private static final String REQUEST_PREFIX = "\n--------------------------------- Request  Info -----------------------------";

    private static final String REQUEST_TAIL   = "\n-----------------------------------------------------------------------------";

    private static final String RESPONSE_PREFIX = "\n--------------------------------- Response Info -----------------------------";

    private static final String RESPONSE_TAIL   = "\n-------------------------------------------------------------------------->>>";

    private static final String CACHED_REQUEST_BODY_OBJECT_KEY = "cachedRequestBodyObject";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        long start = System.currentTimeMillis();
        StringBuilder reqMsg = new StringBuilder();
        StringBuilder resMsg = new StringBuilder();
        // 获取请求信息
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress address = request.getRemoteAddress();
        String method = request.getMethodValue();
        URI uri = request.getURI();
        HttpHeaders headers = request.getHeaders();
        // 获取请求body
        Object cachedRequestBodyObject = exchange.getAttributeOrDefault(CACHED_REQUEST_BODY_OBJECT_KEY, null);
        String params = "";
        if(cachedRequestBodyObject!=null){
            byte[] body = (byte[]) cachedRequestBodyObject;
            params = new String(body);
        }

        // 获取请求query
        Map queryMap = request.getQueryParams();
        String query = JSON.toJSONString(queryMap);

        // 拼接请求日志
        reqMsg.append(REQUEST_PREFIX);
        reqMsg.append("\n header=").append(headers);
        reqMsg.append("\n query=").append(query);
        reqMsg.append("\n params=").append(params);
        reqMsg.append("\n address=").append(address.getHostName()).append(address.getPort());
        reqMsg.append("\n method=").append(method);
        reqMsg.append("\n url=").append(uri.getPath());
        reqMsg.append(REQUEST_TAIL);
        log.info(reqMsg.toString()); // 打印入参日志

        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        resMsg.append(RESPONSE_PREFIX);

        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);//释放掉内存
                        String responseResult = new String(content, Charset.forName("UTF-8"));
                        resMsg.append("\n status=").append(this.getStatusCode());
                        resMsg.append("\n header=").append(this.getHeaders());
                        resMsg.append("\n responseResult=").append(responseResult);
                        resMsg.append(RESPONSE_TAIL);

                        // 计算请求时间
                        long end = System.currentTimeMillis();
                        long time = end - start;
                        resMsg.append("耗时ms:").append(time);
                        log.info(resMsg.toString()); // 打印结果日志
                        return bufferFactory.wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };

        return chain.filter(exchange.mutate().response(decoratedResponse).build());
        //return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1; // 数字越小,执行顺序越高
    }
}

四、全局网关异常配置

package com.its.cloud.handler.gateway;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关全局异常处理类
 *
 * @author huguangjun
 * @className ExceptionHandler
 * @date 2021/1/11
 * @desc 23:03
 */
public class ExceptionHandler extends DefaultErrorWebExceptionHandler {

    public ExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                            ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        int code;
        //Throwable error = super.getError(request);
//        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
//            code = 404;
//        }
//        if (cause instanceof org.springframework.cloud.gateway.support.TimeoutException) {
//            code = 504;
//        }
        //return response(code, this.buildMessage(request, error));
        Map<String, Object> errorAttributes = super.getErrorAttributes(request, options);
        code = Integer.parseInt(errorAttributes.get("status").toString());
        return response(code, this.buildMessage(errorAttributes));
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     *
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        return (Integer) errorAttributes.get("code");
    }

    /**
     * 构建异常信息
     *
     * @param request
     * @param ex
     * @return
     */
    private String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }

    private String buildMessage(Map<String, Object> errorAttributes) {
        return errorAttributes.toString();
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status       状态码
     * @param errorMessage 异常信息
     * @return
     */
    public static Map<String, Object> response(int status, String errorMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("data", "服务器错误");
        return map;
    }
}
package com.its.cloud.config;

import com.its.cloud.handler.gateway.ExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * 全局网关异常配置
 * @author huguangjun
 * @className GlobalGatewayException
 * @date 2021/1/11
 * @desc 22:54
 */
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class GlobalGatewayConfig {
    private final ServerProperties serverProperties;

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    private final List<ViewResolver> viewResolvers;

    private final ServerCodecConfigurer serverCodecConfigurer;

    public GlobalGatewayConfig(ServerProperties serverProperties,
                               ResourceProperties resourceProperties,
                               ObjectProvider<List<ViewResolver>> viewResolversProvider,
                               ServerCodecConfigurer serverCodecConfigurer,
                               ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        ExceptionHandler exceptionHandler = new ExceptionHandler(
                errorAttributes,
                this.resourceProperties,
                this.serverProperties.getError(),
                this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}

五、application.yml 路由和断言配置

注意:配合nacos注册中心使用,该引入nacos-discovery的包就引入。

server:
  port: 80

spring:
  application:
    name: its-gateway
  cloud:
    nacos:
      discovery:
        # 配置nacos服务中心地址
        server-addr: localhost:8848
    gateway:
      httpclient:
        #全局连接超时
        connect-timeout: 10000
        #全局响应超时
        response-timeout: 10s
      discovery:
        locator:
          #开启从注册中心动态创建路由的功能,利用微服务名进行路由
          enabled: true
      routes:
        - id: payment_routh             #路由的id,没有固定规则但要求要唯一,建议配合服务名
          #uri: http://localhost:9001   #匹配后提供服务的路由地址
          uri: lb://its-provider        #匹配后提供服务的路由地址
          #断言中有after、before、between、cookie等,可根据时间来设置生效,也可检测是否带cookie
          predicates:
            - Path=/api/payment/get/**    #断言,路径相匹配的进行路由
          filters:
            # 前缀过滤,默认配置下,我们的请求路径是 http://localhost:9001/payment/get/** 这时会路由到指定的服务
            # 此处配置去掉 1 个路径前缀,再配置上面的 Path=/api/payment/get/**,就能按照 http://localhost/api/payment/get/** 的方式访问了
            - StripPrefix=1
        - id: payment_routh2            #路由的id,没有固定规则但要求要唯一,建议配合服务名
          #uri: http://localhost:9001   #匹配后提供服务的路由地址
          uri: lb://its-provider        #匹配后提供服务的路由地址
          predicates:
            - Path=/api/payment/create/**    #断言,路径相匹配的进行路由
          filters:
            - StripPrefix=1

#把要监控的暴露出来
management:
  endpoints:
    web:
      exposure:
        include: '*'