Browse Source

网关模块首次提交

hdc 1 year ago
parent
commit
efdeed4b1c

+ 35 - 0
cf-gateway/.gitignore

@@ -0,0 +1,35 @@
+HELP.md
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/
+/.mvn/
+/.mvn/

+ 310 - 0
cf-gateway/mvnw

@@ -0,0 +1,310 @@
+#!/bin/sh
+# ----------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# ----------------------------------------------------------------------------
+
+# ----------------------------------------------------------------------------
+# Maven Start Up Batch script
+#
+# Required ENV vars:
+# ------------------
+#   JAVA_HOME - location of a JDK home dir
+#
+# Optional ENV vars
+# -----------------
+#   M2_HOME - location of maven2's installed home dir
+#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
+#     e.g. to debug Maven itself, use
+#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+# ----------------------------------------------------------------------------
+
+if [ -z "$MAVEN_SKIP_RC" ] ; then
+
+  if [ -f /etc/mavenrc ] ; then
+    . /etc/mavenrc
+  fi
+
+  if [ -f "$HOME/.mavenrc" ] ; then
+    . "$HOME/.mavenrc"
+  fi
+
+fi
+
+# OS specific support.  $var _must_ be set to either true or false.
+cygwin=false;
+darwin=false;
+mingw=false
+case "`uname`" in
+  CYGWIN*) cygwin=true ;;
+  MINGW*) mingw=true;;
+  Darwin*) darwin=true
+    # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
+    # See https://developer.apple.com/library/mac/qa/qa1170/_index.html
+    if [ -z "$JAVA_HOME" ]; then
+      if [ -x "/usr/libexec/java_home" ]; then
+        export JAVA_HOME="`/usr/libexec/java_home`"
+      else
+        export JAVA_HOME="/Library/Java/Home"
+      fi
+    fi
+    ;;
+esac
+
+if [ -z "$JAVA_HOME" ] ; then
+  if [ -r /etc/gentoo-release ] ; then
+    JAVA_HOME=`java-config --jre-home`
+  fi
+fi
+
+if [ -z "$M2_HOME" ] ; then
+  ## resolve links - $0 may be a link to maven's home
+  PRG="$0"
+
+  # need this for relative symlinks
+  while [ -h "$PRG" ] ; do
+    ls=`ls -ld "$PRG"`
+    link=`expr "$ls" : '.*-> \(.*\)$'`
+    if expr "$link" : '/.*' > /dev/null; then
+      PRG="$link"
+    else
+      PRG="`dirname "$PRG"`/$link"
+    fi
+  done
+
+  saveddir=`pwd`
+
+  M2_HOME=`dirname "$PRG"`/..
+
+  # make it fully qualified
+  M2_HOME=`cd "$M2_HOME" && pwd`
+
+  cd "$saveddir"
+  # echo Using m2 at $M2_HOME
+fi
+
+# For Cygwin, ensure paths are in UNIX format before anything is touched
+if $cygwin ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --unix "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
+fi
+
+# For Mingw, ensure paths are in UNIX format before anything is touched
+if $mingw ; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME="`(cd "$M2_HOME"; pwd)`"
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
+fi
+
+if [ -z "$JAVA_HOME" ]; then
+  javaExecutable="`which javac`"
+  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
+    # readlink(1) is not available as standard on Solaris 10.
+    readLink=`which readlink`
+    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
+      if $darwin ; then
+        javaHome="`dirname \"$javaExecutable\"`"
+        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
+      else
+        javaExecutable="`readlink -f \"$javaExecutable\"`"
+      fi
+      javaHome="`dirname \"$javaExecutable\"`"
+      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
+      JAVA_HOME="$javaHome"
+      export JAVA_HOME
+    fi
+  fi
+fi
+
+if [ -z "$JAVACMD" ] ; then
+  if [ -n "$JAVA_HOME"  ] ; then
+    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+      # IBM's JDK on AIX uses strange locations for the executables
+      JAVACMD="$JAVA_HOME/jre/sh/java"
+    else
+      JAVACMD="$JAVA_HOME/bin/java"
+    fi
+  else
+    JAVACMD="`which java`"
+  fi
+fi
+
+if [ ! -x "$JAVACMD" ] ; then
+  echo "Error: JAVA_HOME is not defined correctly." >&2
+  echo "  We cannot execute $JAVACMD" >&2
+  exit 1
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+  echo "Warning: JAVA_HOME environment variable is not set."
+fi
+
+CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
+
+# traverses directory structure from process work directory to filesystem root
+# first directory with .mvn subdirectory is considered project base directory
+find_maven_basedir() {
+
+  if [ -z "$1" ]
+  then
+    echo "Path not specified to find_maven_basedir"
+    return 1
+  fi
+
+  basedir="$1"
+  wdir="$1"
+  while [ "$wdir" != '/' ] ; do
+    if [ -d "$wdir"/.mvn ] ; then
+      basedir=$wdir
+      break
+    fi
+    # workaround for JBEAP-8937 (on Solaris 10/Sparc)
+    if [ -d "${wdir}" ]; then
+      wdir=`cd "$wdir/.."; pwd`
+    fi
+    # end of workaround
+  done
+  echo "${basedir}"
+}
+
+# concatenates all lines of a file
+concat_lines() {
+  if [ -f "$1" ]; then
+    echo "$(tr -s '\n' ' ' < "$1")"
+  fi
+}
+
+BASE_DIR=`find_maven_basedir "$(pwd)"`
+if [ -z "$BASE_DIR" ]; then
+  exit 1;
+fi
+
+##########################################################################################
+# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+# This allows using the maven wrapper in projects that prohibit checking in binary data.
+##########################################################################################
+if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Found .mvn/wrapper/maven-wrapper.jar"
+    fi
+else
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
+    fi
+    if [ -n "$MVNW_REPOURL" ]; then
+      jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    else
+      jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    fi
+    while IFS="=" read key value; do
+      case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
+      esac
+    done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
+    if [ "$MVNW_VERBOSE" = true ]; then
+      echo "Downloading from: $jarUrl"
+    fi
+    wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
+    if $cygwin; then
+      wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
+    fi
+
+    if command -v wget > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found wget ... using wget"
+        fi
+        if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+            wget "$jarUrl" -O "$wrapperJarPath"
+        else
+            wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
+        fi
+    elif command -v curl > /dev/null; then
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Found curl ... using curl"
+        fi
+        if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
+            curl -o "$wrapperJarPath" "$jarUrl" -f
+        else
+            curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
+        fi
+
+    else
+        if [ "$MVNW_VERBOSE" = true ]; then
+          echo "Falling back to using Java to download"
+        fi
+        javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
+        # For Cygwin, switch paths to Windows format before running javac
+        if $cygwin; then
+          javaClass=`cygpath --path --windows "$javaClass"`
+        fi
+        if [ -e "$javaClass" ]; then
+            if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Compiling MavenWrapperDownloader.java ..."
+                fi
+                # Compiling the Java class
+                ("$JAVA_HOME/bin/javac" "$javaClass")
+            fi
+            if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
+                # Running the downloader
+                if [ "$MVNW_VERBOSE" = true ]; then
+                  echo " - Running MavenWrapperDownloader.java ..."
+                fi
+                ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
+            fi
+        fi
+    fi
+fi
+##########################################################################################
+# End of extension
+##########################################################################################
+
+export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
+if [ "$MVNW_VERBOSE" = true ]; then
+  echo $MAVEN_PROJECTBASEDIR
+fi
+MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin; then
+  [ -n "$M2_HOME" ] &&
+    M2_HOME=`cygpath --path --windows "$M2_HOME"`
+  [ -n "$JAVA_HOME" ] &&
+    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
+  [ -n "$CLASSPATH" ] &&
+    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
+  [ -n "$MAVEN_PROJECTBASEDIR" ] &&
+    MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
+fi
+
+# Provide a "standardized" way to retrieve the CLI args that will
+# work with both Windows and non-Windows executions.
+MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
+export MAVEN_CMD_LINE_ARGS
+
+WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+exec "$JAVACMD" \
+  $MAVEN_OPTS \
+  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
+  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
+  ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

+ 182 - 0
cf-gateway/mvnw.cmd

@@ -0,0 +1,182 @@
+@REM ----------------------------------------------------------------------------
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements.  See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership.  The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License.  You may obtain a copy of the License at
+@REM
+@REM    https://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied.  See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+@REM ----------------------------------------------------------------------------
+
+@REM ----------------------------------------------------------------------------
+@REM Maven Start Up Batch script
+@REM
+@REM Required ENV vars:
+@REM JAVA_HOME - location of a JDK home dir
+@REM
+@REM Optional ENV vars
+@REM M2_HOME - location of maven2's installed home dir
+@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
+@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
+@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
+@REM     e.g. to debug Maven itself, use
+@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
+@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
+@REM ----------------------------------------------------------------------------
+
+@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
+@echo off
+@REM set title of command window
+title %0
+@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
+@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
+
+@REM set %HOME% to equivalent of $HOME
+if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
+
+@REM Execute a user defined script before this one
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
+@REM check for pre script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
+if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
+:skipRcPre
+
+@setlocal
+
+set ERROR_CODE=0
+
+@REM To isolate internal variables from possible post scripts, we use another setlocal
+@setlocal
+
+@REM ==== START VALIDATION ====
+if not "%JAVA_HOME%" == "" goto OkJHome
+
+echo.
+echo Error: JAVA_HOME not found in your environment. >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+:OkJHome
+if exist "%JAVA_HOME%\bin\java.exe" goto init
+
+echo.
+echo Error: JAVA_HOME is set to an invalid directory. >&2
+echo JAVA_HOME = "%JAVA_HOME%" >&2
+echo Please set the JAVA_HOME variable in your environment to match the >&2
+echo location of your Java installation. >&2
+echo.
+goto error
+
+@REM ==== END VALIDATION ====
+
+:init
+
+@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
+@REM Fallback to current working directory if not found.
+
+set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
+IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
+
+set EXEC_DIR=%CD%
+set WDIR=%EXEC_DIR%
+:findBaseDir
+IF EXIST "%WDIR%"\.mvn goto baseDirFound
+cd ..
+IF "%WDIR%"=="%CD%" goto baseDirNotFound
+set WDIR=%CD%
+goto findBaseDir
+
+:baseDirFound
+set MAVEN_PROJECTBASEDIR=%WDIR%
+cd "%EXEC_DIR%"
+goto endDetectBaseDir
+
+:baseDirNotFound
+set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
+cd "%EXEC_DIR%"
+
+:endDetectBaseDir
+
+IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
+
+@setlocal EnableExtensions EnableDelayedExpansion
+for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
+@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
+
+:endReadAdditionalConfig
+
+SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
+set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
+set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
+
+set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+
+FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
+    IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
+)
+
+@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
+@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
+if exist %WRAPPER_JAR% (
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Found %WRAPPER_JAR%
+    )
+) else (
+    if not "%MVNW_REPOURL%" == "" (
+        SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
+    )
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Couldn't find %WRAPPER_JAR%, downloading it ...
+        echo Downloading from: %DOWNLOAD_URL%
+    )
+
+    powershell -Command "&{"^
+		"$webclient = new-object System.Net.WebClient;"^
+		"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
+		"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
+		"}"^
+		"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
+		"}"
+    if "%MVNW_VERBOSE%" == "true" (
+        echo Finished downloading %WRAPPER_JAR%
+    )
+)
+@REM End of extension
+
+@REM Provide a "standardized" way to retrieve the CLI args that will
+@REM work with both Windows and non-Windows executions.
+set MAVEN_CMD_LINE_ARGS=%*
+
+%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
+if ERRORLEVEL 1 goto error
+goto end
+
+:error
+set ERROR_CODE=1
+
+:end
+@endlocal & set ERROR_CODE=%ERROR_CODE%
+
+if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
+@REM check for post script, once with legacy .bat ending and once with .cmd ending
+if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
+if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
+:skipRcPost
+
+@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
+if "%MAVEN_BATCH_PAUSE%" == "on" pause
+
+if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
+
+exit /B %ERROR_CODE%

+ 77 - 0
cf-gateway/pom.xml

@@ -0,0 +1,77 @@
+<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <artifactId>tofly-parent</artifactId>
+        <groupId>com.tofly</groupId>
+        <version>1.0.3</version>
+    </parent>
+    <artifactId>cf-gateway</artifactId>
+    <version>1.0.0</version>
+    <name>cf-gateway</name>
+    <description>网关</description>
+
+    <dependencies>
+
+        <!--gateway 网关依赖,内置webflux 依赖-->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-gateway</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>com.tofly</groupId>
+            <artifactId>common-redis</artifactId>
+            <version>1.0.3</version>
+        </dependency>
+        <!-- nacos配置中心 -->
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
+        </dependency>
+        <!-- swagger -->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.tofly</groupId>
+            <artifactId>swagger-bootstrap-ui</artifactId>
+            <version>1.9.6</version>
+        </dependency>
+        <!-- 基础功能包 -->
+        <dependency>
+            <groupId>com.tofly</groupId>
+            <artifactId>common-core</artifactId>
+            <version>1.0.3</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <exclusions>
+                <!--排除tomcat依赖-->
+                <exclusion>
+                    <artifactId>*</artifactId>
+                    <groupId>*</groupId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 15 - 0
cf-gateway/src/main/java/com/tofly/gateway/GatewayApplication.java

@@ -0,0 +1,15 @@
+package com.tofly.gateway;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
+
+@SpringBootApplication
+@EnableDiscoveryClient
+public class GatewayApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(GatewayApplication.class, args);
+    }
+
+}

+ 41 - 0
cf-gateway/src/main/java/com/tofly/gateway/balance/LoadBalancerBean.java

@@ -0,0 +1,41 @@
+package com.tofly.gateway.balance;
+
+import org.springframework.cloud.client.loadbalancer.LoadBalanced;
+import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
+import org.springframework.cloud.gateway.config.LoadBalancerProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * @author tuonbed
+ * @date 2020/7/21  17:12
+ */
+@Configuration
+public class LoadBalancerBean {
+    @Bean
+    @LoadBalanced
+    public RestTemplate restTemplate() {
+        return new RestTemplate();
+    }
+
+
+//    @Bean
+//    public IRule getIRule(){
+//        return new ToflyChooseBalancerRule();
+//    }
+
+    @Bean
+    public ToflyLoadBalancerClientFilter userLoadBalanceClientFilter(LoadBalancerClient client, LoadBalancerProperties properties) {
+        return new ToflyLoadBalancerClientFilter(client, properties);
+    }
+
+
+    @Bean
+    public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
+        return redisTemplate.opsForValue();
+    }
+
+}

+ 82 - 0
cf-gateway/src/main/java/com/tofly/gateway/balance/ToflyChooseBalancerRule.java

@@ -0,0 +1,82 @@
+package com.tofly.gateway.balance;
+
+import com.netflix.client.config.IClientConfig;
+import com.netflix.loadbalancer.AbstractLoadBalancerRule;
+import com.netflix.loadbalancer.RoundRobinRule;
+import com.netflix.loadbalancer.Server;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang.math.RandomUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.ValueOperations;
+
+import java.util.List;
+
+/**
+ * @author tuonbed
+ * @date 2020/7/21  16:29
+ */
+//@Component
+@Slf4j
+public class ToflyChooseBalancerRule extends AbstractLoadBalancerRule {
+
+    @Autowired
+    private ValueOperations<String,String> valueOperations;
+
+    @Override
+    public void initWithNiwsConfig(IClientConfig clientConfig) {
+
+    }
+
+    /**
+     * 自定义的选择方法
+     * @param key
+     * @return
+     */
+    @Override
+    public Server choose(Object key) {
+        List<Server> servers = this.getLoadBalancer().getReachableServers();
+        if (servers.isEmpty()) {
+            RoundRobinRule roundRobinRule=new RoundRobinRule();
+            return roundRobinRule.choose(key);
+        }
+        if (servers.size() == 1) {
+            return servers.get(0);
+        }
+        if (key == null) {
+            return randomChoose(servers);
+        }
+        return hashKeyChoose(servers, key);
+    }
+
+    /**
+     * 返回随机实例
+     * @param servers
+     * @return
+     */
+    private Server randomChoose(List<Server> servers) {
+        int randomIndex = RandomUtils.nextInt(servers.size());
+        return servers.get(randomIndex);
+    }
+
+    /**
+     * 自定义的根据规则返回实例
+     * @param servers
+     * @param key
+     * @return
+     */
+    private Server hashKeyChoose(List<Server> servers, Object key) {
+
+        String o = valueOperations.get(key);
+
+        log.info("取得的token:{},调用的端口为:{}",key,o);
+        if(o!=null){
+            for(Server server:servers){
+                if(server.getPort()==Integer.valueOf(o)){
+                    return server;
+                }
+            }
+        }
+        return randomChoose(servers);
+
+    }
+}

+ 79 - 0
cf-gateway/src/main/java/com/tofly/gateway/balance/ToflyLoadBalancerClientFilter.java

@@ -0,0 +1,79 @@
+package com.tofly.gateway.balance;
+
+import com.tofly.common.core.util.StringUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.client.ServiceInstance;
+import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
+import org.springframework.cloud.gateway.config.LoadBalancerProperties;
+import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
+import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.web.server.ServerWebExchange;
+
+import java.net.URI;
+import java.util.concurrent.TimeUnit;
+
+import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
+
+/**
+ * @author tuonbed
+ * @date 2020/7/21  16:19
+ */
+@Slf4j
+public class ToflyLoadBalancerClientFilter extends LoadBalancerClientFilter {
+    @Autowired
+    private StringRedisTemplate redisTemplate;
+
+    public ToflyLoadBalancerClientFilter(LoadBalancerClient loadBalancer, LoadBalancerProperties properties) {
+        super(loadBalancer, properties);
+    }
+
+    @Override
+    protected ServiceInstance choose(ServerWebExchange exchange) {
+//        return loadBalancer.choose(
+//                ((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR)).getHost());
+
+        if (this.loadBalancer instanceof RibbonLoadBalancerClient) {
+            RibbonLoadBalancerClient client = (RibbonLoadBalancerClient) this.loadBalancer;
+            String serviceId = ((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR)).getHost();
+            //这里使用userId做为选择服务实例的key
+            if(serviceId.equalsIgnoreCase("tofly-base")){
+                //这里可以拿到web请求的上下文,可以从header中取出来自己定义的数据。
+                String token = exchange.getRequest().getHeaders().getFirst("Authorization");
+                log.info("从Authorization获取到的token为:{}",token);
+                String access_token = exchange.getRequest().getQueryParams().getFirst("access_token");
+                token=StringUtil.isEmpty(token)?access_token:token;
+                if (!StringUtil.isEmpty(token)) {
+                    token=token.replace("bearer ","");
+                    // 过滤掉轮询接口  TODO 后续改为nacos配置
+                    URI uri = exchange.getRequest().getURI();
+                    String path = uri.getPath();
+                    boolean matches = path.matches("/homeInformation/getTypeDistributionInfo");
+                    boolean matches1 = path.matches("/homeInformation/getCommissionStatisticalInfo");
+                    boolean matches2 = path.matches("/messagepush/page");
+                    if(!matches && !matches1 && !matches2){
+                        // 这里做token续签操作 判断是否需要续期
+                        String redisTokenKey = "tofly_oauth:auth:"+token;
+                        Boolean aBoolean = redisTemplate.hasKey(redisTokenKey);
+                        if(null!=aBoolean && aBoolean){
+                            Long expire = redisTemplate.getExpire(redisTokenKey);
+                            log.info("当前用户为token设置失效时长为:{}",expire);
+                            // 小于一小时续签
+                            if(null!=expire && expire != -2 && expire < 39600L){
+                                redisTemplate.expire(redisTokenKey, 43200, TimeUnit.SECONDS);
+                                log.info("续签操作:{}",redisTokenKey);
+                            }
+                        }
+                    }
+
+
+                    return client.choose(serviceId, token);
+                }
+            }
+        }
+        return super.choose(exchange);
+
+    }
+
+}

+ 63 - 0
cf-gateway/src/main/java/com/tofly/gateway/filter/ErrorHandlerConfiguration.java

@@ -0,0 +1,63 @@
+package com.tofly.gateway.filter;
+
+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 Administrator
+ * @date 2019/10/17  13:15
+ */
+@Configuration
+@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
+public class ErrorHandlerConfiguration {
+
+    private final ServerProperties serverProperties;
+
+    private final ApplicationContext applicationContext;
+
+    private final ResourceProperties resourceProperties;
+
+    private final List<ViewResolver> viewResolvers;
+
+    private final ServerCodecConfigurer serverCodecConfigurer;
+
+    public ErrorHandlerConfiguration(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) {
+        ToflyExceptionHandler exceptionHandler = new ToflyExceptionHandler(
+                errorAttributes,
+                this.resourceProperties,
+                this.serverProperties.getError(),
+                this.applicationContext);
+        exceptionHandler.setViewResolvers(this.viewResolvers);
+        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
+        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
+        return exceptionHandler;
+    }
+}

+ 170 - 0
cf-gateway/src/main/java/com/tofly/gateway/filter/LoginParamFilter.java

@@ -0,0 +1,170 @@
+package com.tofly.gateway.filter;
+
+import com.tofly.common.core.constant.SecurityConstants;
+import com.tofly.common.core.util.HttpURL;
+import com.tofly.common.core.util.StringUtil;
+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.GatewayFilter;
+import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
+import org.springframework.http.server.reactive.ServerHttpRequest;
+import org.springframework.stereotype.Component;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Administrator
+ * @date 2019/10/9  11:52
+ * 登陆接口默认添加clientid
+ * 需要在网关进行配置对哪一个服务进行过滤
+ */
+@Component
+@Slf4j
+public class LoginParamFilter extends AbstractGatewayFilterFactory {
+
+    @Autowired
+    private ValueOperations<String,String> valueOperations;
+
+    @Autowired
+    private RedisTemplate redisTemplate;
+
+    @Value("${tofly.client_Id:tofly}")
+    private String client_Id;
+    @Value("${tofly.client_secret:tofly}")
+    private String client_secret;
+    @Value("${tofly.grant_type:password}")
+    private String grant_type;
+    @Override
+    public GatewayFilter apply(Object config) {
+        return (exchange, chain) -> {
+            ServerHttpRequest request = exchange.getRequest();
+            // 不是登录请求,直接向下执行
+//            if (!StringUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL)) {
+//                return chain.filter(exchange);
+//            }
+            //修改为oauth/login
+            if (!StringUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_LOGIN_URL)
+                && !StringUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL) ) {
+                return chain.filter(exchange);
+            }
+
+            URI uri = exchange.getRequest().getURI();
+            String queryParam = uri.getRawQuery();
+
+            Map paramMap= getParameterMap(queryParam);
+            if(StringUtil.isEmpty((String)paramMap.get("grant_type"))){
+                paramMap.put("grant_type",grant_type);
+            }
+            if(StringUtil.isEmpty((String)paramMap.get("client_id"))){
+                paramMap.put("client_id",client_Id);
+            }
+            if(StringUtil.isEmpty((String)paramMap.get("client_secret"))){
+                paramMap.put("client_secret",client_secret);
+            }
+
+            String project = (String)paramMap.get("project");
+            if(!StringUtil.isEmpty(project)){
+                //valueOperations.set(SecurityConstants.REDIS_LOGIN_LOCK,project);
+                tryLock(SecurityConstants.REDIS_LOGIN_LOCK, project);
+                //redisTemplate.opsForValue().set(SecurityConstants.REDIS_LOGIN_LOCK,project);
+//                Boolean success = redisTemplate.opsForValue().setIfAbsent(SecurityConstants.REDIS_LOGIN_LOCK, project,
+//                        SecurityConstants.REDIS_LOCK_TIME, TimeUnit.MILLISECONDS);
+//                while (!success){
+//                    try {
+//                        Thread.sleep(2000);
+//                    } catch (InterruptedException e) {
+//                        e.printStackTrace();
+//                    }
+//                    success = redisTemplate.opsForValue().setIfAbsent(SecurityConstants.REDIS_LOGIN_LOCK, project,
+//                            SecurityConstants.REDIS_LOCK_TIME, TimeUnit.MILLISECONDS);
+//                }
+            }
+
+            log.info("------------string paramMap:{}",HttpURL.asUrlParams(paramMap));
+            URI newUri = UriComponentsBuilder.fromUri(uri)
+                    .replacePath(SecurityConstants.OAUTH_TOKEN_URL)
+                    .replaceQuery(HttpURL.asUrlParams(paramMap))
+                    .build(true)
+                    .toUri();
+
+            ServerHttpRequest newRequest = exchange.getRequest().mutate().uri(newUri).build();
+            return chain.filter(exchange.mutate().request(newRequest).build());
+        };
+    }
+
+    public Boolean tryLock(String key, String value) {
+        Long start = System.currentTimeMillis();
+        try{
+            Boolean ret=valueOperations.setIfAbsent(key, value, SecurityConstants.REDIS_LOCK_TIME, TimeUnit.MILLISECONDS);
+            while (!ret){
+                try {
+                    Thread.sleep(1000);
+                }catch (InterruptedException e) {
+                        e.printStackTrace();
+                }
+                ret = valueOperations.setIfAbsent(key, value, SecurityConstants.REDIS_LOCK_TIME, TimeUnit.MILLISECONDS);
+            }
+            return true;
+
+        }finally {
+            valueOperations.setIfAbsent(key, value);
+        }
+
+    }
+
+
+    private Map getParameterMap(String queryParam){
+        Map<String, Object> map = new HashMap<String, Object>(0);
+        if (StringUtil.isEmpty(queryParam)) {
+            return map;
+        }
+        String[] params = queryParam.split("&");
+        for (int i = 0; i < params.length; i++) {
+            String[] p = params[i].split("=");
+            if (p.length == 2) {
+                map.put(p[0], p[1]);
+            }
+        }
+        return map;
+    }
+
+
+    private  Map getParameterMap(ServerHttpRequest request) throws UnsupportedEncodingException {
+        // 参数Map
+        Map properties = request.getQueryParams();
+        // 返回值Map
+        Map returnMap = new HashMap();
+        Iterator entries = properties.entrySet().iterator();
+        Map.Entry entry;
+        String name = "";
+        String value = "";
+        while (entries.hasNext()) {
+            entry = (Map.Entry) entries.next();
+            name = (String) entry.getKey();
+            Object valueObj = entry.getValue();
+            if(null == valueObj){
+                value = "";
+            }else if(valueObj instanceof String[]){
+                String[] values = (String[])valueObj;
+                for(int i=0;i<values.length;i++){
+                    value = values[i] + ",";
+                }
+                value = value.substring(0, value.length()-1);
+            }else{
+                value = new String(valueObj.toString().getBytes("iso-8859-1"), "utf-8");
+
+            }
+            returnMap.put(name, value);
+        }
+        return returnMap;
+    }
+}

+ 89 - 0
cf-gateway/src/main/java/com/tofly/gateway/filter/ToflyExceptionHandler.java

@@ -0,0 +1,89 @@
+package com.tofly.gateway.filter;
+
+import lombok.extern.slf4j.Slf4j;
+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.reactive.error.ErrorAttributes;
+import org.springframework.context.ApplicationContext;
+import org.springframework.web.reactive.function.server.*;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Administrator
+ * @date 2019/10/17  13:11
+ */
+@Slf4j
+public class ToflyExceptionHandler extends DefaultErrorWebExceptionHandler {
+    public ToflyExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
+        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
+    }
+
+    /**
+     * 获取异常属性
+     */
+    @Override
+    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
+        int code = 500;
+        Throwable error = super.getError(request);
+        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {
+            code = 404;
+        }
+        return response(code, this.buildMessage(request, error));
+    }
+
+    /**
+     * 指定响应处理方法为JSON处理的方法
+     * @param errorAttributes
+     */
+    @Override
+    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
+        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
+    }
+
+    /**
+     * 根据code获取对应的HttpStatus
+     * @param errorAttributes
+     */
+    @Override
+    protected int getHttpStatus(Map<String, Object> errorAttributes) {
+        return (int) 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();
+    }
+
+    /**
+     * 构建返回的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("result", null);
+        return map;
+    }
+
+}

+ 57 - 0
cf-gateway/src/main/java/com/tofly/gateway/filter/ToflyRequestGlobalFilter.java

@@ -0,0 +1,57 @@
+package com.tofly.gateway.filter;
+
+import com.tofly.common.core.constant.SecurityConstants;
+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.http.server.reactive.ServerHttpRequest;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+import org.springframework.web.server.ServerWebExchange;
+import reactor.core.publisher.Mono;
+
+import java.util.Arrays;
+import java.util.stream.Collectors;
+
+import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
+import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
+
+/**
+ * @author Administrator
+ * @date 2019/9/17  13:54
+ *  全局拦截器,作用所有的微服务
+ *  1. 对请求头中参数进行处理 from 参数进行清洗
+ *  2. 重写StripPrefix = 1,支持全局
+ */
+@Component
+@Slf4j
+public class ToflyRequestGlobalFilter implements GlobalFilter, Ordered {
+    @Override
+    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
+
+
+        // 1. 清洗请求头中from 参数
+        ServerHttpRequest request = exchange.getRequest().mutate()
+                .headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM))
+                .build();
+        // 2. 重写StripPrefix
+        addOriginalRequestUrl(exchange, request.getURI());
+        String rawPath = request.getURI().getRawPath();
+        String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
+                .skip(1L).collect(Collectors.joining("/"));
+        ServerHttpRequest newRequest = request.mutate()
+                .path(newPath)
+                .build();
+        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
+        return chain.filter(exchange.mutate()
+                .request(newRequest.mutate()
+                        .build()).build());
+}
+
+    @Override
+    public int getOrder() {
+        return -100;
+    }
+
+}

+ 49 - 0
cf-gateway/src/main/java/com/tofly/gateway/swagger/SwaggerHandler.java

@@ -0,0 +1,49 @@
+package com.tofly.gateway.swagger;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import reactor.core.publisher.Mono;
+import springfox.documentation.swagger.web.*;
+
+import java.util.Optional;
+
+/**
+ * @author Administrator
+ * @date 2019/9/25  15:06
+ */
+@RestController
+@RequestMapping("/swagger-resources")
+public class SwaggerHandler {
+    @Autowired(required = false)
+    private SecurityConfiguration securityConfiguration;
+    @Autowired(required = false)
+    private UiConfiguration uiConfiguration;
+    private final SwaggerResourcesProvider swaggerResources;
+
+    @Autowired
+    public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
+        this.swaggerResources = swaggerResources;
+    }
+
+
+    @GetMapping("/configuration/security")
+    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
+        return Mono.just(new ResponseEntity<>(
+                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
+    }
+
+    @GetMapping("/configuration/ui")
+    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
+        return Mono.just(new ResponseEntity<>(
+                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
+    }
+
+    @GetMapping("")
+    public Mono<ResponseEntity> swaggerResources() {
+        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
+    }
+}

+ 68 - 0
cf-gateway/src/main/java/com/tofly/gateway/swagger/SwaggerProvider.java

@@ -0,0 +1,68 @@
+package com.tofly.gateway.swagger;
+
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.cloud.gateway.config.GatewayProperties;
+import org.springframework.cloud.gateway.route.RouteLocator;
+import org.springframework.cloud.gateway.support.NameUtils;
+import org.springframework.context.annotation.Primary;
+import org.springframework.stereotype.Component;
+import springfox.documentation.swagger.web.SwaggerResource;
+import springfox.documentation.swagger.web.SwaggerResourcesProvider;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * @author Administrator
+ * @date 2019/9/25  14:18
+ */
+@AllArgsConstructor
+@Slf4j
+@Primary
+@Component
+public class SwaggerProvider implements SwaggerResourcesProvider {
+
+    public static final String API_URI = "/v2/api-docs";
+    private final RouteLocator routeLocator;
+    private final GatewayProperties gatewayProperties;
+
+    private final ToflyRouteManager toflyRouteManager;
+
+    @Override
+    public List<SwaggerResource> get() {
+        List<SwaggerResource> resources = new ArrayList<>();
+        List<String> routes = new ArrayList<>();
+        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
+        gatewayProperties.getRoutes().stream().filter(routeDefinition -> 	routes.contains(routeDefinition.getId()))
+                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
+                        .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
+//                        .filter(predicateDefinition -> !"tofly-auth".equalsIgnoreCase(routeDefinition.getId()))
+                        .filter(predicateDefinition -> !"appdemo".equalsIgnoreCase(routeDefinition.getId()))
+                        .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
+                                predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
+                                        .replace("/**", API_URI)))));
+        /*gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
+                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
+                        .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
+                        .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
+                                predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
+                                        .replace("/**", API_URI)))));*/
+        toflyRouteManager.setRoute();
+        toflyRouteManager.getRouteDefinitions().forEach(routeDefinition -> routeDefinition.getPredicates().stream()
+                .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
+                        predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
+                                .replace("/**", API_URI)))));
+        log.info("list:,{}",resources.stream().map(sw->sw.getName()).collect(Collectors.toList()));
+        return resources;
+    }
+
+    private SwaggerResource swaggerResource(String name, String location) {
+        SwaggerResource swaggerResource = new SwaggerResource();
+        swaggerResource.setName(name);
+        swaggerResource.setLocation(location);
+        swaggerResource.setSwaggerVersion("2.0");
+        return swaggerResource;
+    }
+}

+ 79 - 0
cf-gateway/src/main/java/com/tofly/gateway/swagger/ToflyRouteManager.java

@@ -0,0 +1,79 @@
+package com.tofly.gateway.swagger;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cloud.client.discovery.DiscoveryClient;
+import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
+import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
+import org.springframework.cloud.gateway.route.RouteDefinition;
+import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
+import org.springframework.cloud.gateway.route.RouteLocator;
+import org.springframework.cloud.gateway.support.NameUtils;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.context.ApplicationEventPublisherAware;
+import org.springframework.stereotype.Component;
+import reactor.core.publisher.Mono;
+
+import java.net.URI;
+import java.util.*;
+
+/**
+ * @author tuonbed
+ * @date 2020/7/17  10:20
+ */
+@Component
+@Slf4j
+public class ToflyRouteManager implements ApplicationEventPublisherAware {
+    @Autowired
+    private RouteDefinitionWriter routeDefinitionWriter;
+    @Autowired
+    private DiscoveryClient discoveryClient;
+    @Autowired
+    private RouteLocator routeLocator;
+
+    private List<RouteDefinition> list=new ArrayList<>();
+
+    private ApplicationEventPublisher publisher;
+
+    private final String PRE_SERVER="CompositeDiscoveryClient_";
+
+    @Override
+    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
+        this.publisher = applicationEventPublisher;
+    }
+
+    public void setRoute(){
+        List<String> services = discoveryClient.getServices();
+        Set<String> routes=new HashSet<>();
+        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));;
+        services.stream().filter(s->(!routes.contains(s)&&!s.equalsIgnoreCase("tofly-config")
+                &&!s.equalsIgnoreCase("tofly-eureka") && !s.equalsIgnoreCase("tofly-getway"))).forEach(
+                serverId->{
+                    RouteDefinition definition = new RouteDefinition();
+//                    definition.setId(PRE_SERVER+serverId);
+                    definition.setId(serverId);
+                    URI uri = URI.create("lb://"+serverId);
+                    definition.setUri(uri);
+                    PredicateDefinition predicate = new PredicateDefinition();
+                    predicate.setName("Path");
+                    Map<String, String> predicateParams = new HashMap<>(8);
+                    predicateParams.put(NameUtils.GENERATED_NAME_PREFIX + "0", "/"+serverId+"/**");
+                    predicate.setArgs(predicateParams);
+                    definition.setPredicates(Arrays.asList(predicate));
+                    log.info(".........添加应用:{},",serverId);
+                    list.add(definition);
+                    routeDefinitionWriter.save(Mono.just(definition)).subscribe();
+                    notifyChanged();
+                }
+        );
+    }
+
+    private void notifyChanged() {
+        this.publisher.publishEvent(new RefreshRoutesEvent(this));
+    }
+
+    public List<RouteDefinition> getRouteDefinitions(){
+        return list;
+    }
+
+}

+ 12 - 0
cf-gateway/src/main/resources/application-redis.yml

@@ -0,0 +1,12 @@
+spring:
+  redis:
+    database: 1
+    password:
+    host: 192.168.2.233
+    port: 6379
+    jedis:
+      pool:
+        max-idle: 300
+        min-idle: 100
+        max-active: 500
+        max-wait: 10000

+ 18 - 0
cf-gateway/src/main/resources/application.yml

@@ -0,0 +1,18 @@
+server:
+   port: 10085
+  # 数据源
+spring:
+  profiles:
+    active: redis
+tofly:
+  client_Id: tofly
+  client_secret: tofly
+  grant_type: password
+
+eureka:
+  client:
+    enabled: false
+
+tofly-base:
+  ribbon:
+    NFLoadBalancerRuleClassName: com.tofly.gateway.balance.ToflyChooseBalancerRule

+ 77 - 0
cf-gateway/src/main/resources/bootstrap.yml

@@ -0,0 +1,77 @@
+spring:
+  cloud:
+    config:
+      enabled: false
+    gateway:
+      routes:
+        - id: cf-auth
+          uri: http://localhost:10101
+          predicates:
+            - Path=/auth/**
+          filters:
+            - LoginParamFilter
+        - id: cf-dc
+          uri: lb://cf-dc
+          predicates:
+            - Path=/dc/**
+          filters:
+            - LoginParamFilter
+        - id: cf-base
+          uri: http://localhost:10102
+          predicates:
+            - Path=/base/**
+        - id: cf-xrtymis
+          uri: lb://cf-xrtymis
+          predicates:
+            - Path=/mis/**
+        - id: cf-xrty-gps
+          uri: lb://cf-xrty-gps
+          predicates:
+            - Path=/gps/**
+        - id: cf-xrtygis
+          uri: lb://cf-xrtygis
+          predicates:
+            - Path=/gis/**
+        - id: cf-common-flow
+          uri: lb://cf-common-flow
+          predicates:
+            - Path=/flow/**
+#        - id: cf-fees
+#          uri: lb://cf-fees
+#          predicates:
+#            - Path=/fees/**
+        - id: cf-fees
+          uri: http://localhost:10209
+          predicates:
+            - Path=/fees/**
+      globalcors:
+        corsConfigurations:
+          '[/**]':
+            allowCredentials: true
+            exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"
+            allowedHeaders: "*"
+            allowedOrigins: "*"
+            allowedMethods: "*"
+    nacos:
+      config:
+        enabled: false
+        # nacos配置中心指定空间
+        namespace: ysglxt
+        # nacos部署IP
+        server-addr: 192.168.2.233:8848
+        # 配置后缀
+        file-extension: yaml
+        shared-configs[0]:
+          dataId: public_config_redis.yaml
+      discovery:
+        enabled: false
+        # nacos配置中心指定空间
+        namespace: ysglxt
+        server-addr: 192.168.2.233:8848
+  application:
+    # 该应用在nacos配置中的名称
+    name: cf-gateway
+
+logging:
+  level:
+    com.alibaba.nacos.client.config.impl: WARN

+ 22 - 0
cf-gateway/src/test/java/com/tofly/gateway/GatewayApplicationTests.java

@@ -0,0 +1,22 @@
+package com.tofly.gateway;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.cloud.client.discovery.DiscoveryClient;
+
+import java.util.List;
+
+@SpringBootTest
+class GatewayApplicationTests {
+
+    @Autowired
+    private DiscoveryClient discoveryClient;
+
+    @Test
+    void contextLoads() {
+        List<String> services = discoveryClient.getServices();
+        System.out.println();
+    }
+
+}