• spring gateway给请求添加params


    spring 版本:

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.6.2</version>
        </parent>
        
            <spring.cloud.version>2021.0.0</spring.cloud.version>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    代码

    util

    package com.kittlen.gateway.utils;
    
    import com.kittlen.comm.utils.JsonUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.cloud.gateway.filter.GatewayFilterChain;
    import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
    import org.springframework.cloud.gateway.support.BodyInserterContext;
    import org.springframework.core.io.buffer.DataBuffer;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.codec.HttpMessageReader;
    import org.springframework.http.server.reactive.ServerHttpRequest;
    import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
    import org.springframework.util.StringUtils;
    import org.springframework.web.reactive.function.BodyInserter;
    import org.springframework.web.reactive.function.BodyInserters;
    import org.springframework.web.reactive.function.server.HandlerStrategies;
    import org.springframework.web.reactive.function.server.ServerRequest;
    import org.springframework.web.server.ServerWebExchange;
    import org.springframework.web.util.UriComponentsBuilder;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    
    import java.net.URI;
    import java.util.List;
    import java.util.Map;
    import java.util.function.Function;
    
    /**
     * @author kittlen
     * @version 1.0
     * @date 2022/56/24 11:56
     */
    @Slf4j
    public class RequestParamsUtil {
    
        private List<HttpMessageReader<?>> messageReaders;
    
        public RequestParamsUtil(List<HttpMessageReader<?>> messageReaders) {
            this.messageReaders = messageReaders;
        }
    
        public RequestParamsUtil() {
            this.messageReaders = HandlerStrategies.withDefaults().messageReaders();
        }
    
        /**
         * get请求,添加参数
         * {@link org.springframework.cloud.gateway.filter.factory.AddRequestParameterGatewayFilterFactory}
         *
         * @param exchange
         * @param chain
         * @param params
         * @return
         */
        public Mono<Void> addParameterForGetMethod(ServerWebExchange exchange, GatewayFilterChain chain, Map<String, String> params) {
            URI uri = exchange.getRequest().getURI();
            StringBuilder query = new StringBuilder();
            String originalQuery = uri.getQuery();
            if (StringUtils.hasText(originalQuery)) {
                query.append(originalQuery);
                if (originalQuery.charAt(originalQuery.length() - 1) != '&') {
                    query.append('&');
                }
            }
            for (String key : params.keySet()) {
                query.append(key).append("=").append(params.get(key)).append("&");
            }
            query.deleteCharAt(query.length() - 1);
            try {
                URI newUri = UriComponentsBuilder.fromUri(uri).replaceQuery(query.toString()).build(true).toUri();
                ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri).build();
                return chain.filter(exchange.mutate().request(request).build());
            } catch (Exception e) {
                log.error("Invalid URI query: " + query.toString(), e);
                return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().build()).build());
            }
        }
    
        /**
         * post请求,添加参数
         * {@link org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory}
         *
         * @param exchange
         * @param chain
         * @param params
         * @return
         */
        public Mono<Void> addParameterForPostMethod(ServerWebExchange exchange, GatewayFilterChain chain, Map<String, String> params) {
            ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
            Mono<String> modifiedBody = serverRequest.bodyToMono(String.class)
                    .flatMap(o -> {
                        if (o.startsWith("[")) {
                            // body内容为数组,直接返回
                            return Mono.just(o);
                        }
                        try {
                            Map map = JsonUtil.json2Map(o);
                            map.putAll(params);
                            return Mono.just(JsonUtil.toJson(map));
                        } catch (Exception e) {
                            e.printStackTrace();
                            return Mono.just(o);
                        }
                    })
                    .switchIfEmpty(Mono.defer(() -> {
                        String body = JsonUtil.toJson(params);
                        return Mono.just(body);
                    }));
            BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
            HttpHeaders headers = new HttpHeaders();
            headers.putAll(exchange.getRequest().getHeaders());
            headers.remove(HttpHeaders.CONTENT_LENGTH);
            CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
            return bodyInserter.insert(outputMessage, new BodyInserterContext())
                    .then(Mono.defer(() -> {
                        ServerHttpRequest decorator = decorate(exchange, headers, outputMessage);
                        return chain.filter(exchange.mutate().request(decorator).build());
                    })).onErrorResume((Function<Throwable, Mono<Void>>) throwable -> Mono.error(throwable));
        }
    
        protected ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
                                                      CachedBodyOutputMessage outputMessage) {
            return new ServerHttpRequestDecorator(exchange.getRequest()) {
                @Override
                public HttpHeaders getHeaders() {
                    long contentLength = headers.getContentLength();
                    HttpHeaders httpHeaders = new HttpHeaders();
                    httpHeaders.putAll(headers);
                    if (contentLength > 0) {
                        httpHeaders.setContentLength(contentLength);
                    } else {
                        // TODO: this causes a 'HTTP/1.1 411 Length Required' // on
                        // httpbin.org
                        httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                    }
                    return httpHeaders;
                }
    
                @Override
                public Flux<DataBuffer> getBody() {
                    return outputMessage.getBody();
                }
            };
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146

    filter (主要代码)

    package com.kittlen.gateway.filter;
    
    import com.kittlen.gateway.utils.RequestParamsUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cloud.gateway.filter.GatewayFilterChain;
    import org.springframework.cloud.gateway.filter.GlobalFilter;
    import org.springframework.core.Ordered;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.http.server.reactive.ServerHttpRequest;
    import org.springframework.stereotype.Component;
    import org.springframework.util.CollectionUtils;
    import org.springframework.web.server.ServerWebExchange;
    import reactor.core.publisher.Mono;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    /**
     * @author kittlen
     * @version 1.0
     * @date 2022/46/24 11:46
     */
    @Slf4j
    @Component
    public class AddParamsFilter implements GlobalFilter, Ordered {
    
        public static final int ORDER = 1;
    
        @Autowired
        RequestParamsUtil requestParamsUtil;
    
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            Map<String, String> userInfo = getUserInfo(request.getHeaders());
    
            if (request.getMethod() == HttpMethod.GET) {
                // get请求 处理参数
                return requestParamsUtil.addParameterForGetMethod(exchange, chain, userInfo);
            }
    
            // post请求 处理参数
            if (request.getMethod() == HttpMethod.POST) {
                MediaType contentType = request.getHeaders().getContentType();
                if (MediaType.APPLICATION_JSON.equals(contentType)
                        || MediaType.APPLICATION_JSON_UTF8.equals(contentType)) {
                    // 请求内容为 application json
                    return requestParamsUtil.addParameterForPostMethod(exchange, chain, userInfo);
                }
            }
    
            // put请求 处理参数 走 post 请求流程
            if (request.getMethod() == HttpMethod.PUT) {
                return requestParamsUtil.addParameterForPostMethod(exchange, chain, userInfo);
            }
    
            // delete请求 处理参数 走 get 请求流程
            if (request.getMethod() == HttpMethod.DELETE) {
                return requestParamsUtil.addParameterForGetMethod(exchange, chain, userInfo);
            }
            return chain.filter(exchange);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
  • 相关阅读:
    中国单反相机行业供需趋势及投资风险研究报告
    [Vulnhub] Pinkys-PalaceV1 Squid http proxy+SQI+BOF
    【作业】python课-实验一
    C# —— 逻辑运算符
    m基于PSO粒子群优化的第四方物流的作业整合算法matlab仿真,对比有代理人和无代理人两种模式下最低运输费用、代理人转换费用、运输方式转化费用和时间惩罚费用
    Python梯度提升决策树的方法示例
    基于JSP的房屋租赁系统
    java版直播商城平台规划及常见的营销模式 电商源码/小程序/三级分销+商城免费搭建
    基于8086家具门安全控制系统设计
    Map集合保存数据库
  • 原文地址:https://blog.csdn.net/weixin_44728369/article/details/125445632