• 请求代理转发(三)


    请求代理转发(三)

    书接上回,在内部服务代理其他服务时, 这次使用 webclient 作为请求客户端

    import static org.springframework.web.reactive.HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;
    
    @Slf4j
    @RestController
    public class ProxyController {
    
        @Autowired
        private WebClient.Builder builder;
    
        private WebClient webClient;
    
        public WebClient client() {
            if (webClient == null) {
                synchronized (ProxyController.class) {
                    webClient = builder.build();
                }
            }
            return webClient;
        }
    
    
        /**
         *
         * @param prefix
         * @param exchange
         * @return
         */
        private String path(String prefix, ServerWebExchange exchange) {
            //获取 完整的请求 url
            String path = (String) exchange.getAttributes().get(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            return path.substring(prefix.length());
        }
    
    
        @RequestMapping("/proxy/**")
        public Mono<Void> proxy(ServerWebExchange exchange) {
            ServerHttpRequest request = exchange.getRequest();
            //拼接代理转发的 url
            URI newUri = rebuildURI(exchange);
            HttpMethod method = request.getMethod();
    
            WebClient.RequestBodySpec bodySpec = client()
                            .method(method).uri(newUri)
                            // copy header
                            .headers(httpHeaders -> httpHeaders.addAll(exchange.getRequest().getHeaders()));
            log.info("request url: {}", newUri);
            WebClient.RequestHeadersSpec<?> headersSpec;
            if (requiresBody(method)) {
                headersSpec = bodySpec.body(BodyInserters.fromDataBuffers(request.getBody()));
            } else {
                headersSpec = bodySpec;
            }
            return headersSpec.exchangeToMono(res -> {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().putAll(res.headers().asHttpHeaders());
                response.setStatusCode(res.statusCode());
                if (res == null) {
                    return Mono.empty();
                }
                return exchange.getResponse().writeWith(res.body(BodyExtractors.toDataBuffers()));
            }).doOnError(t -> {
                log.error("proxy error: ", t);
            });
        }
    
        private URI rebuildURI(ServerWebExchange exchange) {
            URI original = exchange.getRequest().getURI();
            String path = path("/proxy", exchange);
            String scheme = "http";
            String host = "localhost";
            int port = 5556;
            //这个方式可以 copy get 请求的参数
            return UriComponentsBuilder.fromUri(original).scheme(scheme).host(host)
                    .port(port).replacePath(path).build(containsEncodedParts(original)).toUri();
        }
    
    
        private boolean requiresBody(HttpMethod method) {
            switch (method) {
                case PUT:
                case POST:
                case PATCH:
                    return true;
                default:
                    return false;
            }
        }
    
    
        public static boolean containsEncodedParts(URI uri) {
            boolean encoded = (uri.getRawQuery() != null && uri.getRawQuery().contains("%"))
                    || (uri.getRawPath() != null && uri.getRawPath().contains("%"));
            // Verify if it is really fully encoded. Treat partial encoded as unencoded.
            if (encoded) {
                try {
                    UriComponentsBuilder.fromUri(uri).build(true);
                    return true;
                } catch (IllegalArgumentException ignored) {
                    if (log.isTraceEnabled()) {
                        log.trace("Error in containsEncodedParts", ignored);
                    }
                }
    
                return false;
            }
    
            return encoded;
        }
    
    
    }
    
    
    • 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

    测试

    controller:

    @GetMapping("/test")
    public Mono<R<String>> hello2(@RequestParam String name) {
        System.out.println("name: " + name);
        if (name.equals("1")){
            throw new RuntimeException("异常了");
        }
        return Mono.justOrEmpty(R.ok("hello"));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    访问代理: http://localhost:5556/proxy/test?name=tom, 结果:

    {
        "data": "hello",
        "msg": "success",
        "code": 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试后发现 ,像 post 表单,json, 上传文件,都正常

    good luck!

  • 相关阅读:
    MCU定位问题(二)
    MySQL表分区
    【高并发】ScheduledThreadPoolExecutor与Timer的区别和简单示例
    Javaweb之SpringBootWeb案例之 Bean管理的第三方Bean的详细解析
    Java基础方法重写
    HTML CSS JS 网页设计作业「我的家乡吉林」
    zookeeper重启,线上微服务全部掉线,怎么回事?
    9k+ Star 简洁好用的开源 Linux 运维管理面板
    Linux bash: ipconfig: command not found解决方法
    【云原生】多网络情况下,Kafka客户端如何选择合适的网络发起请求
  • 原文地址:https://blog.csdn.net/u013887008/article/details/133338818