欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringCloud Gateway全局过滤器统一请求日志打印

程序员文章站 2022-07-10 18:30:04
1.相关maven依赖 org.springframework.boot spring-boot-starter-parent 2.2.0.RELEASE

1.相关maven依赖

 <!--SpringBoot父级工程-->
<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.2.0.RELEASE</version>
     <relativePath/>
 </parent>
 
 <properties>
     <spring-cloud-vesion>Hoxton.RELEASE</spring-cloud-vesion>
     <spring-cloud-alibaba-vesion>2.2.3.RELEASE</spring-cloud-alibaba-vesion>
 </properties>

 <dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-dependencies</artifactId>
             <version>${spring-cloud-vesion}</version>
             <type>pom</type>
             <scope>import</scope>
         </dependency>
         <dependency>
             <groupId>com.alibaba.cloud</groupId>
             <artifactId>spring-cloud-alibaba-dependencies</artifactId>
             <version>${spring-cloud-alibaba-vesion}</version>
             <type>pom</type>
             <scope>import</scope>
         </dependency>
     </dependencies>
 </dependencyManagement>
 
<dependencies>
    <!--GateWay 依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</dependencies>

2.RequestLogFilter全局过滤器

package com.lzq.filter;

import com.lzq.util.JacksonUtil;
import io.netty.buffer.ByteBufAllocator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
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.DataBufferUtils;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * 请求日志过滤器
 *
 * @author 2020/11/10
 */
@Component
@Slf4j
public class RequestLogFilter implements GlobalFilter, Ordered {
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String method = serverHttpRequest.getMethodValue();
        if ("POST".equals(method)) {
            return DataBufferUtils.join(exchange.getRequest().getBody())
                    .flatMap(dataBuffer -> {
                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        String bodyStr = new String(bytes, StandardCharsets.UTF_8);
                        log.info("------------------------------- POST请求参数 ------------------------------------");
                        log.info(bodyStr);
                        //TODO 拿到POST日志后的操作

                        //下面的将请求体再次封装写回到request里,传到下一级,否则,由于请求体已被消费,后续的服务将取不到值
                        URI uri = serverHttpRequest.getURI();
                        ServerHttpRequest request = serverHttpRequest.mutate().uri(uri).build();
                        DataBuffer bodyDataBuffer = this.stringBuffer(bodyStr);
                        Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);

                        request = new ServerHttpRequestDecorator(request) {
                            @Override
                            public Flux<DataBuffer> getBody() {
                                return bodyFlux;
                            }
                        };
                        //封装request,传给下一级
                        return chain.filter(exchange.mutate().request(request).build());
                    });
        } else if ("GET".equals(method)) {
            MultiValueMap<String, String> queryParams = serverHttpRequest.getQueryParams();
            //TODO 得到Get请求的请求参数后,做你想做的事
            log.info("------------------------------- GET请求参数 ------------------------------------");
            log.info(JacksonUtil.toPrettyJSONString(queryParams));
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    private DataBuffer stringBuffer(String value) {
        byte[] bytes = value.getBytes(StandardCharsets.UTF_8);

        NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
        DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
        buffer.write(bytes);
        return buffer;
    }

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

参考文章:https://www.cnblogs.com/hyf-huangyongfei/p/12849406.html

本文地址:https://blog.csdn.net/qq_38229543/article/details/109627763