liyang 1 год назад
Родитель
Сommit
492bb1b7e4

+ 15 - 0
config_fillters/filters-dev.properties

@@ -0,0 +1,15 @@
+#数据库配置
+#db.ywtdrug.url=jdbc:mysql://127.0.0.1:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+#db.ywtdrug.username=root
+#db.ywtdrug.password=123456x
+
+db.ywtdrug.url=jdbc:mysql://rm-wz9a76b4u608w6f0efo.mysql.rds.aliyuncs.com:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+db.ywtdrug.username=ywt_qa
+db.ywtdrug.password=Ywtqa123456x*#
+
+logging.level.root=ERROR
+
+#redis 配置
+redis.address=192.168.3.202:6379
+nacos.address=127.0.0.1:8848
+

+ 6 - 0
config_fillters/filters-preproduct.properties

@@ -0,0 +1,6 @@
+#数据库配置
+db.ywtdrug.url=jdbc:mysql://192.168.3.202:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+db.ywtdrug.username=root
+db.ywtdrug.password=123456x
+
+logging.level.root=DEBUG

+ 7 - 0
config_fillters/filters-product.properties

@@ -0,0 +1,7 @@
+db.ywtdrug.url=jdbc:mysql://rm-wz9rdewzn495u8iwzo.mysql.rds.aliyuncs.com:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+db.ywtdrug.username=ywt_pro
+db.ywtdrug.password=Ywtpro123456x*#
+
+logging.level.root=ERROR
+
+redis.address=172.18.82.227:6339

+ 12 - 0
config_fillters/filters-test.properties

@@ -0,0 +1,12 @@
+#db.ywtdrug.url=jdbc:mysql://rm-wz97y25m3263o6w46o.mysql.rds.aliyuncs.com:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+#db.ywtdrug.username=ywt_qa
+#db.ywtdrug.password=Ywtqa123456x*#
+
+db.ywtdrug.url=jdbc:mysql://rm-wz9a76b4u608w6f0efo.mysql.rds.aliyuncs.com:3306/ywt_drug?characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&autoReconnect=true
+db.ywtdrug.username=ywt_qa
+db.ywtdrug.password=Ywtqa123456x*#
+
+logging.level.root=INFO
+
+#redis \u914D\u7F6E
+redis.address=172.18.82.224:6339

+ 124 - 0
pom.xml

@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <groupId>com.ywt</groupId>
+        <artifactId>ywt-parent</artifactId>
+        <version>1.0.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>ywt-gateway</artifactId>
+    <packaging>jar</packaging>
+
+    <!-- 对组件进行个性化设置 -->
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
+        </dependency>
+       <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-gateway</artifactId>
+           <exclusions>
+               <exclusion>
+                   <artifactId>jul-to-slf4j</artifactId>
+                   <groupId>org.slf4j</groupId>
+               </exclusion>
+               <exclusion>
+                   <artifactId>log4j-to-slf4j</artifactId>
+                   <groupId>org.apache.logging.log4j</groupId>
+               </exclusion>
+               <exclusion>
+                   <artifactId>logback-classic</artifactId>
+                   <groupId>ch.qos.logback</groupId>
+               </exclusion>
+               <exclusion>
+                   <groupId>org.bouncycastle</groupId>
+                   <artifactId>bcprov-jdk15on</artifactId>
+               </exclusion>
+           </exclusions>
+        </dependency>
+        <!--得不加上这个配置,不然会报503-->
+       <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+    </dependencies>
+
+
+    <profiles>
+        <profile>
+            <id>dev</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+            <properties>
+                <active.profile>dev</active.profile>
+            </properties>
+        </profile>
+        <profile>
+            <id>test</id>
+            <properties>
+                <active.profile>test</active.profile>
+            </properties>
+        </profile>
+        <profile>
+            <id>product</id>
+            <properties>
+                <active.profile>product</active.profile>
+            </properties>
+        </profile>
+        <profile>
+            <id>preproduct</id>
+            <properties>
+                <active.profile>preproduct</active.profile>
+            </properties>
+        </profile>
+    </profiles>
+    <build>
+        <filters>
+            <filter>config_fillters/filters-${active.profile}.properties</filter>
+        </filters>
+        <resources>
+            <resource>
+                <directory>src/main/resources</directory>
+                <filtering>true</filtering>
+            </resource>
+        </resources>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <version>3.2</version>
+                <configuration>
+                    <source>1.8</source>
+                    <target>1.8</target>
+                    <encoding>utf-8</encoding>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 17 - 0
src/main/java/com/ywt/gateway/GatewayServiceApplication.java

@@ -0,0 +1,17 @@
+package com.ywt.gateway;
+
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ * 网关启动类
+ */
+@SpringBootApplication
+public class GatewayServiceApplication {
+    public static void main(String[] args) {
+        SpringApplication.run(GatewayServiceApplication.class, args);
+    }
+
+}
+

+ 51 - 0
src/main/java/com/ywt/gateway/configuration/GlobalExceptionConfiguration.java

@@ -0,0 +1,51 @@
+package com.ywt.gateway.configuration;
+
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
+import org.springframework.core.Ordered;
+import org.springframework.core.annotation.Order;
+import org.springframework.core.io.buffer.DataBufferFactory;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.server.reactive.ServerHttpResponse;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ResponseStatusException;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+/**
+ * @company: kayakwise
+ * @author: TWX
+ * @date: 2023/4/18 15:55
+ * @description: 网关全局异常处理器设置响应内容 避免上游xml格式,却返回json
+ */
+@Component
+@Slf4j
+@Order(Ordered.HIGHEST_PRECEDENCE)
+public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {
+    //日志对象
+    @Override //参数1: request response   ex:出现异常时异常对象
+    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
+        log.error("网关出现异常:", ex);
+        // 1.获取响应对象
+        ServerHttpResponse response = exchange.getResponse();
+        // 2.response是否结束  用于多个异常处理时候
+        if (response.isCommitted()) {
+            return Mono.error(ex);
+        }
+        // 3.设置响应头类型
+        response.getHeaders().setContentType(exchange.getRequest().getHeaders().getContentType());
+        // 4.设置响应码
+        if (ex instanceof ResponseStatusException) {
+            response.setStatusCode(((ResponseStatusException) ex).getStatus());
+        } else {
+            response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
+        }
+        // 5.设置响应内容 避免上游xml格式,却返回json
+        return response.writeWith(Mono.fromSupplier(() -> {
+                    DataBufferFactory bufferFactory = response.bufferFactory();
+                    //设置响应到response的数据
+                    return bufferFactory.wrap(new byte[]{});
+                }));
+    }
+}

+ 37 - 0
src/main/java/com/ywt/gateway/decorator/RecorderServerHttpRequestDecorator.java

@@ -0,0 +1,37 @@
+package com.ywt.gateway.decorator;
+
+import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
+import reactor.core.publisher.Flux;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @company: ywt
+ * @author: liy
+ * @date: 2023/10/24 16:18
+ * @description: 用于获取body
+ */
+public class RecorderServerHttpRequestDecorator extends ServerHttpRequestDecorator {
+    private final List<DataBuffer> dataBuffers = new ArrayList<>();
+
+    public RecorderServerHttpRequestDecorator(ServerHttpRequest delegate) {
+        super(delegate);
+        super.getBody().map(dataBuffer -> {
+            dataBuffers.add(dataBuffer);
+            return dataBuffer;
+        }).subscribe();
+    }
+
+    @Override
+    public Flux<DataBuffer> getBody() {
+        return copy();
+    }
+
+    private Flux<DataBuffer> copy() {
+        return Flux.fromIterable(dataBuffers)
+                .map(buf -> buf.factory().wrap(buf.asByteBuffer()));
+    }
+}

+ 143 - 0
src/main/java/com/ywt/gateway/filter/ActionFilter.java

@@ -0,0 +1,143 @@
+/*
+package com.ywt.gateway.filter;
+
+
+
+import org.reactivestreams.Publisher;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.gateway.filter.GatewayFilterChain;
+import org.springframework.cloud.gateway.filter.GlobalFilter;
+import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
+import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
+import org.springframework.core.Ordered;
+import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.http.server.reactive.ServerHttpResponse;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+*/
+/**
+ * 自定义全局过滤器
+ *//*
+
+@Component
+public class ActionFilter implements GlobalFilter, Ordered {
+    private static final Logger log = LoggerFactory.getLogger(ActionFilter.class);
+
+    @Autowired
+    private ModifyRequestBodyGatewayFilterFactory factory;
+
+    */
+/**
+     * 执行过滤器中的业务逻辑
+     *
+     * @param exchange
+     * @param chain
+     * @return
+     *//*
+
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+        String uuid = null;
+
+        ServerHttpRequest request = exchange.getRequest();
+        HttpHeaders headers = request.getHeaders();
+        MediaType contentType = headers.getContentType();
+        log.debug("请求报文类型: {}", getContentType(contentType));
+
+
+        if (StringUtils.isEmpty(contentType)) {
+            return sendError(exchange, HttpStatus.UNSUPPORTED_MEDIA_TYPE, null);
+        }
+
+
+        String uri = request.getPath().value();
+        if (uri.contains("upload")){
+            return chain.filter(exchange);
+        }
+        if (uri.contains("data")){
+            return chain.filter(exchange);
+        }
+        if (uri.contains("download")){
+            return chain.filter(exchange);
+        }
+
+        try {
+            int of = uri.substring(1).indexOf("/");
+            String origin = uri.substring(0, of + 1);
+            log.debug("请求URI: {}", origin);
+            if ("".equals(origin)) {
+                return sendError(exchange, HttpStatus.NOT_FOUND, "未知的请求接口");
+            }
+
+            // 重写报文对象
+            if (uri.startsWith("/esb/inbound")) {
+               // response = servletUtils.getEsbRequest(exchange, getContentType(contentType), entry);
+            }else if (uri.startsWith("/upsys/inbound")) {
+                //response = servletUtils.getEntryXmlMsgRequest(exchange, getContentType(contentType), entry);
+            } else {
+                return sendError(exchange, HttpStatus.NOT_FOUND, "未知的请求接口");
+            }
+
+            // 将原报文放在entry中,并重写请求报文
+            ModifyRequestBodyGatewayFilterFactory.Config config = new ModifyRequestBodyGatewayFilterFactory.Config();
+            config.setRewriteFunction(String.class, String.class, new RequestRewriteFunction(new Object()));
+            config.setContentType(MediaType.APPLICATION_JSON_VALUE);
+            return factory.apply(config).filter(exchange, chain);
+        } catch (Throwable e) {
+            log.error("重定向请求异常", e);
+            return sendError(exchange, HttpStatus.INTERNAL_SERVER_ERROR, null);
+        }
+    }
+
+
+
+    private String getContentType(MediaType mediaType) {
+        return String.join("/", mediaType.getType(), mediaType.getSubtype());
+    }
+
+
+    public Mono<Void> sendError(ServerWebExchange exchange, HttpStatus status, String message) {
+        ServerHttpResponse response = exchange.getResponse();
+        response.setStatusCode(status); // 设置响应码
+        message = message == null ? "" : message.trim();
+        DataBuffer wrap = response.bufferFactory().wrap(message.getBytes());
+        return response.writeWith(Mono.just(wrap));
+    }
+
+    */
+/**
+     * 指定过滤器的执行顺序,数值越小,过滤器的优先级越高,越先执行
+     *
+     * @return
+     *//*
+
+    @Override
+    public int getOrder() {
+        return 1;
+    }
+
+    static class RequestRewriteFunction implements RewriteFunction<String, String> {
+        private final Object entry;
+
+        RequestRewriteFunction(Object entry) {
+            this.entry = entry;
+        }
+
+        @Override
+        public Publisher<String> apply(ServerWebExchange serverWebExchange, String body) {
+            //String content = JSONObject.toJSONString(entry);
+            return Mono.just(entry);
+        }
+    }
+
+}
+*/

+ 57 - 0
src/main/java/com/ywt/gateway/filter/GlobalReponseHeaderFilter.java

@@ -0,0 +1,57 @@
+package com.ywt.gateway.filter;
+
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.gateway.filter.GatewayFilterChain;
+import org.springframework.cloud.gateway.filter.GlobalFilter;
+import org.springframework.cloud.gateway.filter.factory.SetResponseHeaderGatewayFilterFactory;
+import org.springframework.core.Ordered;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+import java.util.List;
+
+/**
+ * 用于处理返回的Content-Type,与请求方保持一致
+ */
+@Component
+public class GlobalReponseHeaderFilter implements GlobalFilter, Ordered {
+    private static final Logger log = LoggerFactory.getLogger(GlobalReponseHeaderFilter.class);
+
+    @Autowired
+    private SetResponseHeaderGatewayFilterFactory factory;
+
+    /**
+     * 执行过滤器中的业务逻辑
+     *
+     * @param exchange
+     * @param chain
+     * @return
+     */
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+        // 修改请求报文头
+        SetResponseHeaderGatewayFilterFactory.NameValueConfig config = new SetResponseHeaderGatewayFilterFactory.NameValueConfig();
+        List<String> strings = exchange.getRequest().getHeaders().get("Content-Type");
+        String contentType = strings.get(0);
+        config.setName("Content-Type");
+        config.setValue(contentType);
+        return factory.apply(config).filter(exchange, chain);
+    }
+
+
+    /**
+     * 指定过滤器的执行顺序,数值越小,过滤器的优先级越高,越先执行
+     *
+     * @return
+     */
+    @Override
+    public int getOrder() {
+        return Ordered.LOWEST_PRECEDENCE;
+    }
+
+
+}

+ 54 - 0
src/main/java/com/ywt/gateway/filter/GlobalRequestHeaderFilter.java

@@ -0,0 +1,54 @@
+package com.ywt.gateway.filter;
+
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.gateway.filter.GatewayFilterChain;
+import org.springframework.cloud.gateway.filter.GlobalFilter;
+import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
+import org.springframework.cloud.gateway.filter.factory.SetRequestHeaderGatewayFilterFactory;
+import org.springframework.core.Ordered;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+/**
+ * 用于处理转发的Content-Type,统一为application/json
+ */
+@Component
+public class GlobalRequestHeaderFilter implements GlobalFilter, Ordered {
+    private static final Logger log = LoggerFactory.getLogger(GlobalRequestHeaderFilter.class);
+
+    @Autowired
+    private SetRequestHeaderGatewayFilterFactory factory;
+
+    /**
+     * 执行过滤器中的业务逻辑
+     *
+     * @param exchange
+     * @param chain
+     * @return
+     */
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+        // 修改请求报文头
+        AbstractNameValueGatewayFilterFactory.NameValueConfig config = new AbstractNameValueGatewayFilterFactory.NameValueConfig();
+        config.setName("Content-Type");
+        config.setValue("application/json");
+        return factory.apply(config).filter(exchange, chain);
+    }
+
+
+    /**
+     * 指定过滤器的执行顺序,数值越小,过滤器的优先级越高,越先执行
+     *
+     * @return
+     */
+    @Override
+    public int getOrder() {
+        return Ordered.LOWEST_PRECEDENCE;
+    }
+
+
+}

+ 103 - 0
src/main/java/com/ywt/gateway/filter/RequestParamGlobalFilter.java

@@ -0,0 +1,103 @@
+package com.ywt.gateway.filter;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+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.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.stereotype.Component;
+import org.springframework.web.reactive.function.server.HandlerStrategies;
+import org.springframework.web.reactive.function.server.ServerRequest;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+import java.util.List;
+
+/**
+ * @company: kayakwise
+ * @author: TWX
+ * @date: 2023/4/14 16:09
+ * @description: 用于获取body
+ */
+@Component
+public class RequestParamGlobalFilter implements GlobalFilter, Ordered {
+
+    private static final Logger log = LoggerFactory.getLogger(RequestParamGlobalFilter.class);
+
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+
+        /**
+         * save request path and serviceId into gateway context
+         */
+        ServerHttpRequest request = exchange.getRequest();
+        HttpHeaders headers = request.getHeaders();
+
+        // 处理参数
+        long contentLength = headers.getContentLength();
+        if (contentLength > 0) {
+            return readBody(exchange, chain);
+        }
+
+        return chain.filter(exchange);
+    }
+
+
+    /**
+     * default HttpMessageReader
+     */
+    private static final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
+    /**
+     * ReadJsonBody
+     *
+     * @param exchange
+     * @param chain
+     * @return
+     */
+    private Mono<Void> readBody(ServerWebExchange exchange, GatewayFilterChain chain) {
+        /**
+         * join the body
+         */
+        return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
+            byte[] bytes = new byte[dataBuffer.readableByteCount()];
+            dataBuffer.read(bytes);
+            DataBufferUtils.release(dataBuffer);
+            Flux<DataBuffer> cachedFlux = Flux.defer(() -> {
+                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
+                DataBufferUtils.retain(buffer);
+                return Mono.just(buffer);
+            });
+            /**
+             * repackage ServerHttpRequest
+             */
+            ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
+                @Override
+                public Flux<DataBuffer> getBody() {
+                    return cachedFlux;
+                }
+            };
+            /**
+             * mutate exchage with new ServerHttpRequest
+             */
+            ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
+            /**
+             * read body string with default messageReaders
+             */
+            return ServerRequest.create(mutatedExchange, messageReaders).bodyToMono(String.class)
+                    .doOnNext(objectValue -> {
+                        log.debug("[GatewayContext]Read JsonBody:{}", objectValue);
+                    }).then(chain.filter(mutatedExchange));
+        });
+    }
+    @Override
+    public int getOrder() {
+        return HIGHEST_PRECEDENCE;
+    }
+}

+ 77 - 0
src/main/java/com/ywt/gateway/filter/RouteFilter.java

@@ -0,0 +1,77 @@
+/*
+package com.ywt.gateway.filter;
+
+
+import com.kayakwise.dcep.utils.ServletUtils;
+import com.kayakwise.enums.DcpActionEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.cloud.gateway.filter.GatewayFilterChain;
+import org.springframework.cloud.gateway.filter.GlobalFilter;
+import org.springframework.cloud.gateway.route.Route;
+import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
+import org.springframework.core.Ordered;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.stereotype.Component;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+*/
+/**
+ * 路由 根据参数修改路由信息
+ *//*
+
+@Component
+public class RouteFilter implements GlobalFilter, Ordered {
+    private static final Logger log = LoggerFactory.getLogger(RouteFilter.class);
+
+    private static final Pattern ESB_SERVICE_CODE_PATTERN = Pattern.compile("<SERVICE_CODE>([^<]+)</SERVICE_CODE>");
+
+    private static final Pattern ESB_SERVICE_SCENE_PATTERN = Pattern.compile("<SERVICE_SCENE>([^<]+)</SERVICE_SCENE>");
+
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+        ServerHttpRequest serverHttpRequest = exchange.getRequest();
+        // 获取从请求参数获取serviceCode 和 serviceScene
+        String uri = serverHttpRequest.getPath().value();
+        if(!uri.startsWith("/esb/inbound")){
+           return   chain.filter(exchange);
+        }
+        exchange.getRequest().getBody();
+        String content = ServletUtils.getBody(serverHttpRequest);
+        if (content == null) {
+            return   chain.filter(exchange);
+        }
+        Matcher m = ESB_SERVICE_CODE_PATTERN.matcher(content);
+        if (!m.find()) {
+            return   chain.filter(exchange);
+        }
+        String serviceCode = m.group(1);
+        Matcher m1 = ESB_SERVICE_SCENE_PATTERN.matcher(content);
+        if (!m1.find()) {
+            return   chain.filter(exchange);
+        }
+        String serviceScene = m1.group(1);
+        //String serviceName = DcpActionEnum.getServiceByServiceCodeAndScene(serviceCode+serviceScene);
+        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
+        Route newRoute = Route.async()
+                    .asyncPredicate(route.getPredicate())
+                    .filters(route.getFilters())
+                    .id(route.getId())
+                    .order(route.getOrder())
+                    .uri("lb://" + serviceName)
+                    .build();
+        exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
+        return chain.filter(exchange);
+    }
+
+    @Override
+    public int getOrder() {
+        return -1;
+    }
+
+}
+*/

+ 548 - 0
src/main/java/com/ywt/gateway/utils/ServletUtils.java

@@ -0,0 +1,548 @@
+/*
+package com.ywt.gateway.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.kayakwise.dcep.decorator.RecorderServerHttpRequestDecorator;
+import com.kayakwise.enums.ChannelCodeEnum;
+import com.kayakwise.enums.DcpActionEnum;
+import com.kayakwise.enums.MsgSNEnum;
+import com.kayakwise.extend.PlatformConstant;
+import com.kayakwise.frame.api.base.DcpsMesgHeadModel;
+import com.kayakwise.frame.util.DcpsMsgHeadUtils;
+import com.kayakwise.frame.util.JsonUtils;
+import com.kayakwise.frame.util.LogUtils;
+import com.kayakwise.models.entity.EntryRequest;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.ThreadContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.core.io.buffer.DataBuffer;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.http.server.reactive.ServerHttpResponse;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+import java.nio.CharBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+报文中转处理工具类
+public class ServletUtils {
+	private static final Logger log = LoggerFactory.getLogger(ServletUtils.class);
+
+	protected static final String CHARSET_UTF_8 = "UTF-8";
+	protected static final String CHARSET_GBK = "GBK";
+	private static final Pattern MSGCD_PATTERN = Pattern.compile("<msgCd>([^<]+)</msgCd>");
+
+	private static final Pattern ESB_SERVICE_CODE_PATTERN = Pattern.compile("<SERVICE_CODE>([^<]+)</SERVICE_CODE>");
+
+	private static final Pattern ESB_SERVICE_SCENE_PATTERN = Pattern.compile("<SERVICE_SCENE>([^<]+)</SERVICE_SCENE>");
+
+
+	private static final Pattern DCEP_MSGTP_PATTERN = Pattern
+			.compile("<head:MsgTp>([^<]+)</head:MsgTp>|<MsgTp>([^<]+)</MsgTp>");
+	private static final Pattern DCEP_MSGSN_PATTERN = Pattern
+			.compile("<head:MsgSN>([^<]+)</head:MsgSN>|<MsgSN>([^<]+)</MsgSN>");
+
+	private static final Pattern p = Pattern.compile("^[A-Za-z0-9_\\+/]+$");
+	private static final String badStr = "and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|"
+			+ "char|declare|sitename|net user|xp_cmdshell|or|like|and|exec|create|"
+			+ "table|from|grant|use|group_concat|column_name|"
+			+ "information_schema.columns|table_schema|union|where|order|by";
+
+	private static List<Pattern> sqlKeyWords = new ArrayList<>();
+
+	static {
+		String keywords1[] = badStr.split("\\|");
+		for (String keywords : keywords1) {
+			sqlKeyWords.add(Pattern.compile(".*\\s" + keywords + "\\s.*"));
+		}
+	}
+
+	public Mono<Void> getEntryRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name, content;
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 从请求URL获取接口名
+			String path = request.getURI().getPath();
+			if (path.contains("wf")) {
+				name = path;
+			} else {
+				String[] action = path.split("/", -1);
+				name = action[action.length - 1];
+			}
+			log.info("请求接口:{}", name);
+			if (name == null) {
+				return sendError(exchange, HttpStatus.NOT_FOUND, "");
+			}
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			log.info("\n\n<----record begin: {}", content.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+			String uuid = ThreadContext.get(PlatformConstant.LOG_UUID_KEY);
+			LogUtils.logPrintStart(LogUtils.LOG_TYPE_BEGIN, ChannelCodeEnum.SC99.getValue(), LogUtils.LOG_LOCAL_DCP, "",
+					uuid, uuid, name, DcpActionEnum.getName(name), content);
+		} catch (Throwable e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+		entryRequest.setPrefix("");
+		entryRequest.setAction(name);
+		entryRequest.setActionNm(DcpActionEnum.getName(name));
+		entryRequest.setContent(content);
+		entryRequest.setContentType(contentType);
+		return null;
+	}
+
+	public Mono<Void> sendError(ServerWebExchange exchange, org.springframework.http.HttpStatus status, String message) {
+		ServerHttpResponse response = exchange.getResponse();
+		response.setStatusCode(status); // 设置响应码
+		message = message == null ? "" : message.trim();
+		DataBuffer wrap = response.bufferFactory().wrap(message.getBytes());
+		return response.writeWith(Mono.just(wrap));
+	}
+
+	public static String getBody(ServerHttpRequest request) {
+		AtomicReference<String> requestBody = new AtomicReference<>("");
+		RecorderServerHttpRequestDecorator requestDecorator = new RecorderServerHttpRequestDecorator(request);
+		Flux<DataBuffer> body = requestDecorator.getBody();
+		body.subscribe(buffer -> {
+			CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
+			requestBody.set(charBuffer.toString());
+		});
+		return requestBody.get();
+	}
+
+
+	*/
+/**
+	 * 上游系统为xml报文
+	 *//*
+
+	public Mono<Void> getEntryXmlMsgRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name, content;
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 从请求URL获取接口名
+			String path = request.getURI().getPath();
+			String[] action = path.split("/", -1);
+			name = action[3];
+			log.info("请求接口:{}", name);
+			if (name == null) {
+				return sendError(exchange, HttpStatus.NOT_FOUND, "");
+			}
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			log.debug("\n\n<----record begin: \r\n{}",
+					content.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+			String sourceSystem = content.substring(content.indexOf("<esb:UserReferenceNo>") + 21,
+					content.indexOf("</esb:UserReferenceNo>"));
+			String logFlowRefNo = content.substring(content.indexOf("<esb:SystemReferenceNo>") + 23,
+					content.indexOf("</esb:SystemReferenceNo>"));
+			String logFlowReqNo = content.substring(content.indexOf("<esb:RequestSystemID>") + 21,
+					content.indexOf("</esb:RequestSystemID>"));
+			LogUtils.logPrintStart(LogUtils.LOG_TYPE_BEGIN, sourceSystem, LogUtils.LOG_LOCAL_DCP, "", logFlowRefNo,
+					logFlowReqNo, name, DcpActionEnum.getName(name), content);
+		} catch (Throwable e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		entryRequest.setActionNm(DcpActionEnum.getName(name));
+		entryRequest.setContent(content);
+		entryRequest.setContentType(contentType);
+
+		return null;
+	}
+
+	*/
+/**
+	 * 行里ESB请求进入
+	 *//*
+
+	public Mono<Void> getEsbRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name, content;
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			//log.info("\n\n<----record begin: \r\n{}",
+			//		content.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+			content = content.replaceAll("\\\\r","").replaceAll("\\\\n","").replaceAll("\\\\t","");
+			content = content.replace("\\","");
+			Matcher m = ESB_SERVICE_CODE_PATTERN.matcher(content);
+			if (!m.find()) {
+				log.info("获取ESB服务编号失败,原始报文:{}", content);
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			String serviceCode = m.group(1);
+			log.info("ESB服务编号:{}", serviceCode);
+			Matcher m1 = ESB_SERVICE_SCENE_PATTERN.matcher(content);
+			if (!m1.find()) {
+				log.info("获取报文编号失败,ESB服务编号报文格式错误:{}", content);
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			String serviceScene = m1.group(1);
+			log.info("ESB服务场景编号:{}", serviceScene);
+			name = DcpActionEnum.getValueByServiceCodeAndScene(serviceCode+serviceScene);
+			log.info("请求接口:{}", name);
+			if (name == null) {
+				return sendError(exchange, HttpStatus.NOT_FOUND, "");
+			}
+			String sourceSystem = content.substring(content.indexOf("<CONSUMER_ID>") + 6,
+					content.indexOf("</CONSUMER_ID>"));
+			String logFlowReqNo = content.substring(content.indexOf("<CONSUMER_SEQ_NO>") + 22,
+					content.indexOf("</CONSUMER_SEQ_NO>"));
+			LogUtils.logPrintStart(LogUtils.LOG_TYPE_BEGIN, sourceSystem, LogUtils.LOG_LOCAL_DCP, "", "",
+					logFlowReqNo, name, DcpActionEnum.getName(name), content);
+		} catch (Throwable e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+		String reqXml = content.substring(content.indexOf("<?xml"));
+		log.info("请求报文体:{}", reqXml.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+		Map<String, String> map = new HashMap<>();
+		map.put("reqXml", reqXml);
+		entryRequest.setContent(JsonUtils.mapToJson(map));
+		entryRequest.setContentType("ESB");
+		entryRequest.setActionNm(DcpActionEnum.getName(name));
+		entryRequest.setAction(name);
+		entryRequest.setPrefix("");
+		return null;
+	}
+
+
+	*/
+/**
+	 * DCPS报文请求解析
+	 * @param exchange
+	 * @param contentType
+	 * @param entryRequest
+	 * @return
+	 *//*
+
+	public Mono<Void> getDcpsRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name = "", content;
+		DcpsMesgHeadModel headModel = null;
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			log.debug("\n\n<----record begin: {}", content.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+			// 从报文头中截取报文编号-接口名
+			if (content.indexOf("{H:") >= 0) {
+				String mesgHead = content.substring(content.indexOf("{H:"));
+				mesgHead = mesgHead.substring(0, mesgHead.indexOf("}") + 1);
+				String mesgType = mesgHead.length() >= 78 ? mesgHead.substring(58, 78).trim() : "";
+				log.info("请求报文编号:{}", mesgType);
+				if (mesgType == null || "".equals(mesgType)) {
+					return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+				}
+				name = mesgType.replace(".", "_");
+
+				// 解析报文头
+				headModel = new DcpsMesgHeadModel();
+				DcpsMsgHeadUtils.parseMsgHeader(mesgHead, headModel);
+			}
+
+			if (content.indexOf("{S:") >= 0) {
+				String signContent = content.substring(content.indexOf("{S:"));
+				signContent = signContent.substring(0, signContent.indexOf("}") + 1);
+				log.info("签名域:{}", signContent);
+				DcpsMsgHeadUtils.parseSignInfo(signContent, headModel);
+			}
+			String logFlowReqNo = content.substring(content.indexOf("<MsgId>") + 7, content.indexOf("</MsgId>"));
+			LogUtils.logPrintStart(LogUtils.LOG_TYPE_BEGIN, LogUtils.LOG_LOCAL_DCPS, LogUtils.LOG_LOCAL_DCP, "",
+					headModel.getMesgID(), logFlowReqNo, name, MsgSNEnum.getName(name), content);
+		} catch (Throwable e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+		// 报文体
+		String reqXml = content.substring(content.indexOf("<?xml"));
+		log.info("请求报文体:{}", reqXml.replaceAll("[\\s&&[^\r\n]]*(?:[\r\n][\\s&&[^\r\n]]*)+", ""));
+		Map<String, String> map = new HashMap<>();
+		map.put("reqXml", reqXml);
+		map.put("reqHead", JsonUtils.objectToJson(headModel));
+
+		entryRequest.setAction(name);
+		entryRequest.setActionNm(DcpActionEnum.getName(name));
+		entryRequest.setPrefix("r_");
+		entryRequest.setContent(JsonUtils.mapToJson(map));
+		entryRequest.setContentType("application/json");
+		return null;
+	}
+
+	public Mono<Void> getDcepRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name = "", content, signature;
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				log.error("报文读取异常,请检查!");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			Matcher msgTPm = DCEP_MSGTP_PATTERN.matcher(content);
+			if (!msgTPm.find()) {
+				log.error("获取报文编号失败,请检查!");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			Matcher msgSnPm = DCEP_MSGSN_PATTERN.matcher(content);
+			if (!msgTPm.find()) {
+				log.error("获取报文编号失败,请检查!");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			String msgTp = msgTPm.group(1);
+			name = msgTp.toUpperCase().replace(".", "_");
+			String msgSn = msgSnPm.group(1);
+			signature = request.getHeaders().getFirst("Signature");
+			log.info("msgSn:{} xml:{} signature:{}", msgSn, content, signature);
+			// TODO 待完善数研所数据获取
+//			String logFlowReqNo = content.substring(content.indexOf("<MsgId>") + 7, content.indexOf("</MsgId>"));
+//			logPrintStart(LOG_TYPE_BEGIN, LOG_LOCAL_DCPS, LOG_LOCAL_DCP, "", headModel.getMesgID(), logFlowReqNo, "",
+//				
+		} catch (Throwable e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		Map<String, String> map = new HashMap<>();
+		map.put("reqXml", content);
+		map.put("signature", signature);
+		entryRequest.setAction(name);
+		entryRequest.setPrefix("R_");
+		entryRequest.setContent(JsonUtils.mapToJson(map));
+		entryRequest.setContentType("application/json");
+		return null;
+	}
+
+	public Mono<Void> getNdpsRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+		String name = "", content;
+
+		try {
+			ServerHttpRequest request = exchange.getRequest();
+			// 读取请求报文
+			content = getBody(request);
+			if (content == null) {
+				log.info("未读取到请求报文");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+
+			Matcher m = MSGCD_PATTERN.matcher(content);
+			if (!m.find()) {
+				log.info("获取报文编号失败,农信银报文格式错误:{}", content);
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+			String msgCd = m.group(1);
+			log.info("报文编号:{}", msgCd);
+			name = msgCd.toUpperCase().replace(".", "_");
+			// TODO 待完善农信数据获取
+//			String logFlowReqNo = content.substring(content.indexOf("<MsgId>") + 7, content.indexOf("</MsgId>"));
+//			logPrintStart(LOG_TYPE_BEGIN, LOG_LOCAL_DCPS, LOG_LOCAL_DCP, "", headModel.getMesgID(), logFlowReqNo, "",
+//					name, "", "", "", "", content);
+		} catch (Exception e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+		// 报文体
+		String reqXml = content.substring(content.indexOf("<?xml"));
+		log.info("请求报文体:{}", reqXml);
+		Map<String, String> map = new HashMap<>();
+		map.put("reqXml", reqXml);
+
+		entryRequest.setAction(name);
+		entryRequest.setPrefix("R_");
+		entryRequest.setContent(JsonUtils.mapToJson(map));
+		entryRequest.setContentType("application/json");
+		return null;
+	}
+
+	public Mono<Void> getUwapRequest(ServerWebExchange exchange, String contentType, EntryRequest entryRequest) {
+
+		String name = "", context;
+		ServerHttpRequest request = exchange.getRequest();
+
+		try {
+			// 读取请求报文
+			context = getBody(request);
+			if (context == null) {
+				log.info("未读取到请求报文");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+		} catch (Exception e) {
+			log.error("读取请求报文异常", e);
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		JSONObject requestObj = null;
+		JSONObject requestObjHeader = null;
+		JSONObject requestObjBody = null;
+		try {
+			requestObj = JSON.parseObject(context);
+			String msgHeader = requestObj.getString("msgHeader");
+			String msgBody = requestObj.getString("msgBody");
+			requestObjHeader = JSON.parseObject(msgHeader);
+			requestObjBody = JSON.parseObject(msgBody);
+			if (null == requestObj || null == requestObjHeader) {
+				log.error("报文解析失败,非法的JSON串,JSON无法解析!");
+				return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+			}
+
+			// TODO 待完善Uwap数据获取
+//			String logFlowReqNo = content.substring(content.indexOf("<MsgId>") + 7, content.indexOf("</MsgId>"));
+//			logPrintStart(LOG_TYPE_BEGIN, LOG_LOCAL_DCPS, LOG_LOCAL_DCP, "", headModel.getMesgID(), logFlowReqNo, "",
+//				
+		} catch (Exception e) {
+			log.error("报文解析失败,非法的JSON串,JSON无法解析!");
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		// 获取HEARD里的内容
+		String TOKEN = String.valueOf(request.getHeaders().get("TOKEN"));
+		String ORG = String.valueOf(request.getHeaders().get("ORG"));
+		String SERVICEID = String.valueOf(request.getHeaders().get("SERVICEID"));
+		String USERID = String.valueOf(request.getHeaders().get("USERID"));
+		String WIDTOKEN = String.valueOf(request.getHeaders().get("WIDTOKEN"));
+		try {
+//            String msgType = requestObjHeader.getString("mesgType");// 交易码
+			name = SERVICEID.replace(".", "_");
+		} catch (Exception e) {
+			log.info("获取报文编号失败");
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+		Map<String, Object> reqMerge = mergeRequest(requestObjHeader, requestObjBody);
+		if (null == reqMerge) {
+			log.info("获取报文内容失败");
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		reqMerge.put("TOKEN", TOKEN);
+		reqMerge.put("SERVICEID", SERVICEID);
+		reqMerge.put("USERID", USERID);
+		reqMerge.put("ORG", ORG);
+		reqMerge.put("WIDTOKEN", WIDTOKEN);
+
+		try {
+			log.info("SQL注入、Xss注入检查...");
+			proXSSAndSqlInject(JSON.parseObject(JsonUtils.mapToJson(reqMerge)));
+		} catch (Exception e) {
+			log.error("非法请求内容");
+			return sendError(exchange, HttpStatus.BAD_REQUEST, "");
+		}
+
+		entryRequest.setContentType("application/json");
+		entryRequest.setAction(name);
+		entryRequest.setPrefix("r_");
+		entryRequest.setContent(JsonUtils.mapToJson(reqMerge));
+
+		return null;
+	}
+
+	*/
+/**
+	 * 合并到一个map中
+	 *
+	 * @param requestObjHeader
+	 * @param requestObjBody
+	 * @return
+	 *//*
+
+	private static Map<String, Object> mergeRequest(JSONObject requestObjHeader, JSONObject requestObjBody) {
+		if (null == requestObjHeader) {
+			return null;
+		}
+		Map<String, Object> msgHeader = JsonUtils.jsonToMap(requestObjHeader.toJSONString());
+
+		Map<String, Object> reqMerge = new HashMap<String, Object>();
+		for (String key : msgHeader.keySet()) {
+			reqMerge.put(key, msgHeader.get(key));
+		}
+		if (null != requestObjBody) {
+			Map<String, Object> msgBody = JsonUtils.jsonToMap(requestObjBody.toJSONString());
+			for (String key : msgBody.keySet()) {
+				reqMerge.put(key, msgBody.get(key));
+			}
+		}
+		return reqMerge;
+	}
+
+
+
+
+
+	private static void proXSSAndSqlInject(JSONObject jo) throws Exception {
+		proXSSAndSqlInject(null, null, jo);
+	}
+
+	private static void proXSSAndSqlInject(JSONObject jo, String key, Object value) throws Exception {
+		if (value instanceof JSONObject) {
+			JSONObject subJo = (JSONObject) value;
+			for (Entry<String, Object> entry : subJo.entrySet()) {
+				String subKey = entry.getKey();
+				Object subVal = entry.getValue();
+				proXSSAndSqlInject(subJo, subKey, subVal);
+			}
+		} else if (value instanceof JSONArray) {
+			for (Object subObj : (JSONArray) value) {
+				if (subObj instanceof JSONObject) {
+					proXSSAndSqlInject(null, null, (JSONObject) subObj);
+				}
+			}
+		} else {
+			cleanXSSAndSqlInject(jo, key, value);
+		}
+
+	}
+
+	// 防XSS
+	private static void cleanXSSAndSqlInject(JSONObject json, String key, Object value) throws Exception {
+		json.replace(key, cleanXSSAndSqlInject(value));
+	}
+
+	// 防XSS
+	private static Object cleanXSSAndSqlInject(Object value) throws Exception {
+		if (value == null) {
+			return null;
+		}
+		String val = String.valueOf(value);
+		if (StringUtils.isBlank(val)) {
+			return value;
+		}
+		if (p.matcher(val).matches()) {
+			return value;
+		}
+
+		for (Pattern sqlKey : sqlKeyWords) {
+			if (sqlKey.matcher(val).matches()) {
+				log.error("SQL注入检查不通过");
+				throw new Exception("报文非法!");
+			}
+		}
+		// 去掉javascript关键要素
+		return val.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("<", "& lt;").replaceAll(">", "& gt;")
+				.replaceAll("eval\\((.*)\\)", "").replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"")
+				.replaceAll("script", "");
+	}
+
+}
+*/

+ 38 - 0
src/main/resource/application.yml

@@ -0,0 +1,38 @@
+server:
+  port: 21545
+spring:
+  application:
+    name: gateway-service
+  cloud:
+    nacos:
+      discovery:
+        server-addr: ${nacos.address}
+        group: ${nacos.group}
+        namespace: ${nacos.namespace}
+        username: ${nacos.username}
+        password: ${nacos.password}
+        metadata: # 保证微服务5s内能快速响应上线线
+          preserved.heart.beat.interval: 1000 # 该实例在客户端上报心跳的间隔时间,单位为毫秒,默认为5s
+          preserved.heart.beat.timeout: 5000 # 该实例在不发送心跳后,从健康到不健康的时间,单位为毫秒,默认为15s
+          preserved.ip.delete.timeout: 5000 # 该实例在不发送心跳后,被nacos下掉该实例的时间,单位为毫秒
+    loadbalancer:
+      cache:
+        ttl: 5s # 客户端缓存时间 默认35s
+      health-check:
+        interval: 5s # Interval for rerunning the HealthCheck scheduler. Default 25s
+        refetch-instances-interval: 5s # Interval for refetching available service instances. Default 25
+    gateway:
+      httpclient:
+        connect-timeout: 1000
+        response-timeout: 55s
+      routes:
+        # 配置路由,可以配置多个
+        # ESB请求接入 在过滤器中动态修改URI 参数
+        - id: trans-service-from-esb  # 自定义路由的ID 保持唯一
+          uri: lb://act-trans-service  # 目标服务地址。动态路由 这里使用服务名的方式,gateway会帮我们去注册中心中获取服务列表
+          predicates: # 路由条件,这里使用了Path作为路由条件(断言)
+            - Path=/esb/inbound
+          filters: # 配置路由过滤器
+            - RewritePath=/esb/inbound, /gateway/front
+
+