├── .gitignore ├── LICENSE.txt ├── README.md ├── config-repo ├── README.md ├── application.yml ├── dev │ └── application-dev.yml ├── mc-config-client-dev.yml ├── mc-config-client-pro.yml ├── mc-config-client-test.yml ├── mc-user-dev.properties ├── mc-user-pro.properties ├── mc-user-test.properties ├── pro │ └── application-pro.yml └── test │ └── application-test.yml ├── mvnw ├── mvnw.cmd ├── pom.xml ├── spring-cloud-admin-client ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── admin │ │ └── AdminClientApplication.java │ └── resources │ └── application.yml ├── spring-cloud-admin-server ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── admin │ │ └── AdminServerApplication.java │ └── resources │ └── application.yml ├── spring-cloud-alibaba ├── notes.txt ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── alibaba │ │ ├── AlibabaApplication.java │ │ ├── controller │ │ └── UserController.java │ │ ├── demo │ │ └── NacosConfigDemo.java │ │ ├── event │ │ ├── ConfigTask.java │ │ └── SpringEventDemo.java │ │ └── scheduled │ │ ├── ScheduledLockConfig.java │ │ └── SpringJob.java │ └── resources │ ├── application.yml │ ├── bootstrap.yml.bak │ ├── default │ └── default.properties │ └── service │ └── service.yml ├── spring-cloud-common ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── leone │ └── cloud │ └── common │ ├── beans │ ├── goods │ │ └── GoodsVO.java │ ├── order │ │ ├── OrderVO.java │ │ └── item │ │ │ └── OrderItemVO.java │ └── user │ │ ├── UserAddVO.java │ │ ├── UserEditVO.java │ │ └── UserVO.java │ ├── entity │ ├── Goods.java │ ├── Order.java │ ├── OrderItem.java │ └── User.java │ └── utils │ ├── EntityFactory.java │ └── RandomValue.java ├── spring-cloud-config-apollo ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── apollo │ │ ├── ApolloApplication.java │ │ └── config │ │ └── ApolloConfigService.java │ └── resources │ └── application.properties ├── spring-cloud-config-client ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── config │ │ ├── ConfigClientApplication.java │ │ └── controller │ │ └── ConfigController.java │ └── resources │ ├── application.yml │ └── bootstrap.yml ├── spring-cloud-config-server-bus ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── config │ │ ├── ConfigServerBusApp.java │ │ └── controller │ │ └── ConfigController.java │ └── resources │ └── application.yml ├── spring-cloud-config-server ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── config │ │ ├── ConfigServerApplication.java │ │ └── filter │ │ ├── CustomerRequestWrapper.java │ │ └── WebHookFilter.java │ └── resources │ ├── application.yml │ ├── application.yml1.bak │ ├── application.yml2.bak │ ├── application.yml3.bak │ └── application.yml4.bak ├── spring-cloud-eureka ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── eureka │ │ └── EurekaApplication.java │ └── resources │ └── application.yml ├── spring-cloud-gateway ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── gateway │ │ ├── GatewayApplication.java │ │ ├── config │ │ └── GatewayConfiguration.java │ │ └── filter │ │ └── PreGatewayFilter.java │ └── resources │ └── application.yml ├── spring-cloud-hystrix-feign ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── hystrix │ │ ├── HystrixFeignApplication.java │ │ ├── controller │ │ └── HystrixController.java │ │ ├── fallback │ │ ├── UserFeignFallback.java │ │ └── UserFeignFallbackFactory.java │ │ └── feign │ │ └── UserFeign.java │ └── resources │ ├── application.yml │ └── config.properties ├── spring-cloud-order ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── order │ │ ├── OrderApplication.java │ │ ├── config │ │ ├── HttpClientConfig.java │ │ ├── HystrixConfig.java │ │ ├── LoadBalancerConfig.java │ │ └── RestTemplateConfig.java │ │ ├── controller │ │ ├── HystrixController.java │ │ ├── LoadBalancerController.java │ │ └── OrderController.java │ │ ├── function │ │ ├── CircuitBreakerTest.java │ │ ├── SemaphoreCommandTest.java │ │ ├── ThreadPoolCommandTest.java │ │ └── TimeOutCommandTest.java │ │ └── service │ │ ├── FeignOrderService.java │ │ ├── OrderService.java │ │ └── UserService.java │ └── resources │ └── application.yml ├── spring-cloud-ribbon-hystrix ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ ├── RibbonHystrixApplication.java │ │ └── cloud │ │ └── ribbon │ │ ├── controller │ │ └── OrderController.java │ │ └── entity │ │ └── User.java │ └── resources │ ├── application.yml │ └── config.properties ├── spring-cloud-sidecar ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── sidecar │ │ └── SidecarApplication.java │ └── resources │ └── application.yml ├── spring-cloud-sleuth ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── sleuth │ │ └── SleuthApplication.java │ └── resources │ └── application.yml ├── spring-cloud-stream ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── stream │ │ ├── StreamApplication.java │ │ ├── controller │ │ └── MessageController.java │ │ └── message │ │ ├── Consumer.java │ │ ├── Processor.java │ │ ├── Sink.java │ │ └── Source.java │ └── resources │ └── application.yml ├── spring-cloud-turbine ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── turbine │ │ └── TurbineApplication.java │ └── resources │ ├── application.yml │ └── config.properties ├── spring-cloud-user ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── leone │ │ └── cloud │ │ └── user │ │ ├── UserApplication.java │ │ ├── config │ │ ├── FeignConfig.java │ │ └── RibbonConfig.java │ │ ├── controller │ │ ├── FeignController.java │ │ ├── RibbonController.java │ │ ├── UserController.java │ │ └── ZkController.java │ │ ├── feign │ │ └── OrderFeignService.java │ │ └── service │ │ ├── UserService.java │ │ └── impl │ │ └── UserServiceImpl.java │ └── resources │ ├── application.yml │ ├── bootstrap.yml │ └── static │ └── index.html └── spring-cloud-zuul ├── pom.xml └── src └── main ├── java └── com │ └── leone │ └── cloud │ └── zuul │ ├── ZuulApplication.java │ └── filter │ ├── ErrorZuulFilter.java │ ├── PostZuulFilter.java │ ├── PreZuulFilter.java │ └── RoutingZuulFilter.java └── resources ├── application.yml ├── application.yml1.bak └── bootstrap.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # maven ignore 2 | target/ 3 | *.jar 4 | *.war 5 | *.zip 6 | *.tar 7 | *.tar.gz 8 | 9 | # eclipse ignore 10 | .settings/ 11 | .project 12 | .classpath 13 | 14 | # idea ignore 15 | .idea 16 | .idea/ 17 | *.ipr 18 | *.iml 19 | *.iws 20 | 21 | # temp ignore 22 | *.log 23 | *.cache 24 | *.diff 25 | *.patch 26 | *.tmp 27 | 28 | # system ignore 29 | .DS_Store 30 | Thumbs.db 31 | 32 | # else 33 | .springBeans 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Cloud 2 | 3 | user -> gateway -> order 4 | 5 | ## eureka 注册中心 6 | 7 | ## cloud-user 8 | 整合了ribbon feign zookeeper consul 9 | 10 | ## cloud-order 11 | 整合了hystrix nacos loadbalancer httpExchange -------------------------------------------------------------------------------- /config-repo/README.md: -------------------------------------------------------------------------------- 1 | # config-repo 2 | 3 | #### 项目介绍 4 | Spring Cloud config repository 5 | 6 | #### 软件架构 7 | spring cloud 微服务框架配置中心 8 | -------------------------------------------------------------------------------- /config-repo/application.yml: -------------------------------------------------------------------------------- 1 | profile: profile-defalut-refresh 2 | name: application.yml 3 | leval: master 4 | -------------------------------------------------------------------------------- /config-repo/dev/application-dev.yml: -------------------------------------------------------------------------------- 1 | profile: dev 2 | filename: dev/application-dev.yml 3 | level: master 4 | 5 | name: james -------------------------------------------------------------------------------- /config-repo/mc-config-client-dev.yml: -------------------------------------------------------------------------------- 1 | profile: dev 2 | filename: application-dev.yml 3 | level: master 4 | 5 | name: james -------------------------------------------------------------------------------- /config-repo/mc-config-client-pro.yml: -------------------------------------------------------------------------------- 1 | profile: pro 2 | filename: application-pro.yml 3 | level: master 4 | 5 | name: jack -------------------------------------------------------------------------------- /config-repo/mc-config-client-test.yml: -------------------------------------------------------------------------------- 1 | profile: test 2 | filename: application-test.yml 3 | level: master 4 | 5 | name: andy -------------------------------------------------------------------------------- /config-repo/mc-user-dev.properties: -------------------------------------------------------------------------------- 1 | profile=dev 2 | filename=user-dev.properties 3 | level=master 4 | 5 | name=james -------------------------------------------------------------------------------- /config-repo/mc-user-pro.properties: -------------------------------------------------------------------------------- 1 | profile=pro 2 | filename=user-pro.properties 3 | level=master 4 | 5 | name=jack -------------------------------------------------------------------------------- /config-repo/mc-user-test.properties: -------------------------------------------------------------------------------- 1 | profile=test 2 | filename=user-test.properties 3 | level=master 4 | 5 | name=andy -------------------------------------------------------------------------------- /config-repo/pro/application-pro.yml: -------------------------------------------------------------------------------- 1 | profile: pro 2 | filename: pro/application-pro.yml 3 | level: master 4 | 5 | name: jack -------------------------------------------------------------------------------- /config-repo/test/application-test.yml: -------------------------------------------------------------------------------- 1 | profile: test 2 | filename: test/application-test.yml 3 | level: master 4 | 5 | name: andy -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.leone.cloud 7 | spring-cloud-examples 8 | 2.0.0.RELEASE 9 | 10 | pom 11 | 12 | 13 | 14 | 15 | 16 | spring-cloud-eureka 17 | spring-cloud-user 18 | spring-cloud-order 19 | spring-cloud-alibaba 20 | spring-cloud-ribbon-hystrix 21 | spring-cloud-zuul 22 | spring-cloud-turbine 23 | spring-cloud-gateway 24 | spring-cloud-sidecar 25 | spring-cloud-config-server 26 | spring-cloud-config-client 27 | spring-cloud-config-server-bus 28 | spring-cloud-stream 29 | spring-cloud-admin-server 30 | spring-cloud-admin-client 31 | spring-cloud-sleuth 32 | spring-cloud-common 33 | spring-cloud-hystrix-feign 34 | spring-cloud-config-apollo 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /spring-cloud-admin-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-admin-client 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-dependencies 24 | 3.3.5 25 | pom 26 | import 27 | 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-dependencies 32 | 2023.0.3 33 | pom 34 | import 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.boot 44 | spring-boot-starter-web 45 | 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-starter-netflix-eureka-client 50 | 51 | 52 | 53 | de.codecentric 54 | spring-boot-admin-starter-client 55 | 3.3.5 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-actuator 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-compiler-plugin 70 | 3.8.0 71 | 72 | 17 73 | 17 74 | UTF-8 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /spring-cloud-admin-client/src/main/java/com/leone/cloud/admin/AdminClientApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.admin; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | /** 8 | *

9 | * 10 | * @author Leone 11 | * @since 2018-10-11 12 | **/ 13 | @EnableDiscoveryClient 14 | @SpringBootApplication 15 | public class AdminClientApplication { 16 | public static void main(String[] args) { 17 | SpringApplication.run(AdminClientApplication.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-cloud-admin-client/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8762 3 | 4 | eureka: 5 | client: 6 | serviceUrl: 7 | defaultZone: http://localhost:8761/eureka/ 8 | spring: 9 | application: 10 | name: admin-client 11 | 12 | management: 13 | endpoints: 14 | web: 15 | exposure: 16 | include: '*' 17 | endpoint: 18 | health: 19 | show-details: always 20 | -------------------------------------------------------------------------------- /spring-cloud-admin-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-admin-server 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-dependencies 24 | 3.3.5 25 | pom 26 | import 27 | 28 | 29 | 30 | org.springframework.cloud 31 | spring-cloud-dependencies 32 | 2023.0.3 33 | pom 34 | import 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | org.springframework.cloud 44 | spring-cloud-starter-netflix-eureka-client 45 | 46 | 47 | 48 | de.codecentric 49 | spring-boot-admin-starter-server 50 | 3.3.5 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-compiler-plugin 61 | 3.8.0 62 | 63 | 17 64 | 17 65 | UTF-8 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /spring-cloud-admin-server/src/main/java/com/leone/cloud/admin/AdminServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.admin; 2 | 3 | import de.codecentric.boot.admin.server.config.EnableAdminServer; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | 8 | /** 9 | *

10 | * 11 | * @author Leone 12 | * @since 2018-10-11 13 | **/ 14 | @EnableAdminServer 15 | //@EnableDiscoveryClient 16 | @SpringBootApplication 17 | public class AdminServerApplication { 18 | public static void main(String[] args) { 19 | SpringApplication.run(AdminServerApplication.class, args); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-cloud-admin-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 6000 3 | spring: 4 | application: 5 | name: admin-server 6 | #eureka: 7 | # client: 8 | # serviceUrl: 9 | # defaultZone: http://localhost:8761/eureka -------------------------------------------------------------------------------- /spring-cloud-alibaba/notes.txt: -------------------------------------------------------------------------------- 1 | 1.spring-boot2.4新增spring.config.import 2 | spring: 3 | config: 4 | import: 5 | # 导入classpath下default目录下的default.properties配置文件 6 | - classpath:/default/default.properties 7 | # 导入classpath下service目录下的service.yml配置文件 8 | - classpath:/service/service.yml -------------------------------------------------------------------------------- /spring-cloud-alibaba/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-alibaba 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-dependencies 25 | 3.3.5 26 | pom 27 | import 28 | 29 | 30 | 31 | org.springframework.cloud 32 | spring-cloud-dependencies 33 | 2023.0.3 34 | pom 35 | import 36 | 37 | 38 | 39 | com.alibaba.cloud 40 | spring-cloud-alibaba-dependencies 41 | 2023.0.1.3 42 | 43 | pom 44 | import 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-web 55 | 56 | 57 | 58 | 59 | com.alibaba.cloud 60 | spring-cloud-starter-alibaba-nacos-discovery 61 | 62 | 63 | 64 | 65 | com.alibaba.cloud 66 | spring-cloud-starter-alibaba-nacos-config 67 | 68 | 69 | 70 | org.springframework.cloud 71 | spring-cloud-starter-bootstrap 72 | 3.0.2 73 | 74 | 75 | 76 | org.springframework.boot 77 | spring-boot-starter-actuator 78 | 79 | 80 | 81 | com.leone.cloud 82 | spring-cloud-common 83 | 2.0.0.RELEASE 84 | 85 | 86 | 87 | net.javacrumbs.shedlock 88 | shedlock-spring 89 | 4.23.0 90 | 91 | 92 | 93 | net.javacrumbs.shedlock 94 | shedlock-provider-jdbc-template 95 | 4.23.0 96 | 97 | 98 | 99 | org.springframework.boot 100 | spring-boot-starter-jdbc 101 | 102 | 103 | 104 | mysql 105 | mysql-connector-java 106 | 8.0.33 107 | 108 | 109 | 110 | com.alibaba.cloud 111 | spring-cloud-starter-alibaba-sentinel 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | org.apache.maven.plugins 121 | maven-compiler-plugin 122 | 3.8.0 123 | 124 | 17 125 | 17 126 | UTF-8 127 | 128 | 129 | 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/AlibabaApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba; 2 | 3 | import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | 9 | /** 10 | * @author Leone 11 | * @since 2018-04-07 12 | **/ 13 | @EnableScheduling 14 | @EnableSchedulerLock(defaultLockAtMostFor = "3m") 15 | @EnableDiscoveryClient 16 | @SpringBootApplication 17 | public class AlibabaApplication { 18 | public static void main(String[] args) { 19 | SpringApplication.run(AlibabaApplication.class, args); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.controller; 2 | 3 | import com.leone.cloud.common.entity.User; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.cloud.context.config.annotation.RefreshScope; 6 | import org.springframework.web.bind.annotation.*; 7 | 8 | import java.util.Map; 9 | 10 | /** 11 | * @author Leone 12 | * @since 2018-03-07 13 | **/ 14 | @RefreshScope 15 | @RestController 16 | public class UserController { 17 | 18 | @Value("${alibaba.name:def-name}") 19 | private String name; 20 | 21 | @Value("${alibaba.age:1}") 22 | private Integer age; 23 | 24 | // @Autowired 25 | // private DiscoveryClient discoveryClient; 26 | 27 | // @GetMapping("/eureka-instance") 28 | // public String serviceUrl() { 29 | // InstanceInfo instance = eurekaClient.getNextServerFromEureka("SPRINGCLOUD-PROVIDER", false); 30 | // return instance.getHomePageUrl(); 31 | // } 32 | // 33 | // @GetMapping("/eureka-info") 34 | // public ServiceInstance serviceInfo() { 35 | // ServiceInstance info = discoveryClient.getLocalServiceInstance(); 36 | // return info; 37 | // } 38 | 39 | @GetMapping("/api/user/{id}") 40 | public User getUser(@PathVariable("id") int id) { 41 | return new User(); 42 | } 43 | 44 | @GetMapping("/setting") 45 | public Map setting() { 46 | return Map.of("name", name, "age", age); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/demo/NacosConfigDemo.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.demo; 2 | 3 | import com.alibaba.nacos.api.NacosFactory; 4 | import com.alibaba.nacos.api.config.ConfigService; 5 | import com.alibaba.nacos.api.exception.NacosException; 6 | 7 | import java.util.Properties; 8 | 9 | public class NacosConfigDemo { 10 | public static void main(String[] args) { 11 | try { 12 | // 设置Nacos服务器地址 13 | Properties properties = new Properties(); 14 | properties.setProperty("serverAddr", "127.0.0.1:8848"); 15 | properties.setProperty("username", "nacos"); 16 | properties.setProperty("password", "nacos"); 17 | properties.setProperty("namespace", "8578b490-d369-4c39-b45e-ef3788e5b473"); 18 | 19 | // 创建ConfigService实例 20 | ConfigService configService = NacosFactory.createConfigService(properties); 21 | 22 | // 定义配置ID与分组 23 | String dataId = "cloud-alibaba-test.yaml"; 24 | String group = "common"; 25 | 26 | // 读取配置 27 | String content = configService.getConfig(dataId, group, 5000L); 28 | 29 | // 输出配置内容 30 | System.out.println("配置内容: \n" + content); 31 | } catch (NacosException e) { 32 | e.printStackTrace(); 33 | System.err.println("读取Nacos配置时发生错误"); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/event/ConfigTask.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.event; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.cloud.context.config.annotation.RefreshScope; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.scheduling.annotation.EnableScheduling; 8 | import org.springframework.scheduling.annotation.Scheduled; 9 | 10 | /** 11 | *

12 | * 13 | * @author leone 14 | * @since 2024-11-21 15 | **/ 16 | @Slf4j 17 | @RefreshScope 18 | @Configuration 19 | @EnableScheduling 20 | public class ConfigTask { 21 | 22 | @Value(value = "${alibaba.name}") 23 | private String alibabaName; 24 | 25 | @Value("${count}") 26 | private Integer count; 27 | 28 | @Value(value = "${spring.application.name}") 29 | private String appName; 30 | 31 | @Value(value = "${defaultVal}") 32 | private String defaultVal; 33 | 34 | @Value(value = "${service}") 35 | private String service; 36 | 37 | @Value(value = "${test}") 38 | private String testVal; 39 | 40 | @Scheduled(fixedDelay = 100 * 1000) 41 | private void config1() { 42 | System.out.println(alibabaName == null ? "None" : alibabaName); 43 | System.out.println(count); 44 | } 45 | 46 | @Scheduled(fixedDelay = 10 * 1000) 47 | private void config2() { 48 | log.info("defaultVal: {} service: {} testVal: {}", 49 | defaultVal, service, testVal); 50 | } 51 | 52 | 53 | } -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/event/SpringEventDemo.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.event; 2 | 3 | import org.springframework.context.ApplicationEvent; 4 | import org.springframework.context.ApplicationEventPublisher; 5 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.event.EventListener; 8 | 9 | /** 10 | * @author Leone 11 | * @since 2018-07-30 12 | **/ 13 | public class SpringEventDemo { 14 | public static void main(String[] args) { 15 | // 创建 Annotation 驱动的 Spring 应用上下文 16 | AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 17 | // 注册到EventConfiguration 到spring容器 18 | context.register(EventConfiguration.class); 19 | context.refresh(); 20 | ApplicationEventPublisher publisher = context; 21 | // 发布事件 22 | publisher.publishEvent(new MyApplicationEvent("hello world")); 23 | 24 | } 25 | 26 | private static class MyApplicationEvent extends ApplicationEvent { 27 | public MyApplicationEvent(String source) { 28 | super(source); 29 | } 30 | } 31 | 32 | @Configuration 33 | public static class EventConfiguration { 34 | @EventListener 35 | public void onEvent(MyApplicationEvent event) { 36 | System.out.println("监听事件" + event); 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/scheduled/ScheduledLockConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.scheduled; 2 | 3 | import java.util.TimeZone; 4 | import javax.sql.DataSource; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | 11 | import net.javacrumbs.shedlock.core.LockProvider; 12 | import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; 13 | 14 | @Configuration 15 | public class ScheduledLockConfig { 16 | 17 | @Autowired 18 | private DataSource dataSource; 19 | 20 | @Bean 21 | public LockProvider lockProvider() { 22 | return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder() 23 | .withJdbcTemplate(new JdbcTemplate(dataSource)) 24 | .withTimeZone(TimeZone.getTimeZone("UTC")) 25 | .build()); 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/java/com/leone/cloud/alibaba/scheduled/SpringJob.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.alibaba.scheduled; 2 | 3 | import org.springframework.scheduling.annotation.Scheduled; 4 | import org.springframework.stereotype.Component; 5 | 6 | import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; 7 | 8 | import java.time.LocalDateTime; 9 | import java.time.format.DateTimeFormatter; 10 | 11 | @Component 12 | public class SpringJob { 13 | 14 | private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 15 | 16 | /** 17 | * 每5分钟跑一次 18 | */ 19 | @Scheduled(cron = "0 */5 * * * ?") 20 | @SchedulerLock(name = "SpringJob.job1", lockAtMostFor = "2m", lockAtLeastFor = "1m") 21 | public void job1() { 22 | System.out.println("time=" + LocalDateTime.now().format(df) + " do job1..."); 23 | } 24 | 25 | /** 26 | * 每5秒跑一次 27 | */ 28 | @Scheduled(fixedRate = 5000) 29 | @SchedulerLock(name = "SpringJob.job2", lockAtMostFor = "4s", lockAtLeastFor = "4s") 30 | public void job2() { 31 | System.out.println("time=" + LocalDateTime.now().format(df) + " do job2..."); 32 | } 33 | 34 | /** 35 | * 上次跑完之后隔5秒再跑 36 | */ 37 | @Scheduled(fixedDelay = 5000) 38 | @SchedulerLock(name = "SpringJob.job3", lockAtMostFor = "4s", lockAtLeastFor = "4s") 39 | public void job3() throws InterruptedException { 40 | System.out.println("time=" + LocalDateTime.now().format(df) + " do job3..."); 41 | Thread.sleep(10000); 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | #alibaba: 2 | # name: ${alibaba.name} 3 | 4 | alibaba: 5 | name: 'def-name' 6 | 7 | management: 8 | endpoint: 9 | health: 10 | show-details: always 11 | endpoints: 12 | web: 13 | exposure: 14 | include: '*' 15 | 16 | spring: 17 | application: 18 | name: nacos-config-example 19 | cloud: 20 | nacos: 21 | config: 22 | serverAddr: 127.0.0.1:8848 23 | username: nacos 24 | password: nacos 25 | config: 26 | import: 27 | # 导入nacos中的配置 28 | - nacos:nacos-config-example.properties?refresh=true 29 | # 导入classpath下default目录下的default.properties配置文件 30 | - classpath:/default/default.properties 31 | # 导入classpath下service目录下的service.yml配置文件 32 | - classpath:/service/service.yml 33 | - optional:/Users/leone/Downloads/test.yml 34 | 35 | datasource: 36 | url: jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=utf-8&useSSL=false 37 | username: root 38 | password: 123456 39 | driver-class: com.mysql.cj.jdbc.Driver 40 | 41 | 42 | logging: 43 | level: 44 | com.alibaba.cloud.nacos.configdata: debug 45 | 46 | 47 | 48 | 49 | 50 | #nacos: 51 | # server-addr: 127.0.0.1:8848 52 | # namespace: 8578b490-d369-4c39-b45e-ef3788e5b473 53 | # username: nacos 54 | # password: nacos -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/resources/bootstrap.yml.bak: -------------------------------------------------------------------------------- 1 | management: 2 | endpoints: 3 | web: 4 | exposure: 5 | include: refresh,health 6 | 7 | spring: 8 | application: 9 | name: cloud-alibaba 10 | profiles: 11 | active: test 12 | cloud: 13 | nacos: 14 | discovery: 15 | server-addr: 127.0.0.1:8848 16 | namespace: 8578b490-d369-4c39-b45e-ef3788e5b473 17 | username: nacos 18 | password: nacos 19 | config: 20 | server-addr: 127.0.0.1:8848 21 | namespace: 8578b490-d369-4c39-b45e-ef3788e5b473 22 | username: nacos 23 | password: nacos 24 | group: common 25 | file-extension: yaml 26 | #自定义配置,比shared-configs优先级高 27 | extension-configs: 28 | # - data-id: ${spring.application.name}-${spring.profiles.active}.yaml 29 | - data-id: cloud-alibaba-test.yaml 30 | group: common 31 | refresh: true 32 | shared-configs: 33 | - data-id: redis-test.yaml 34 | group: common 35 | refresh: true -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/resources/default/default.properties: -------------------------------------------------------------------------------- 1 | defaultVal=99 -------------------------------------------------------------------------------- /spring-cloud-alibaba/src/main/resources/service/service.yml: -------------------------------------------------------------------------------- 1 | service: 2 | test-service -------------------------------------------------------------------------------- /spring-cloud-common/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-common 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | org.projectlombok 21 | lombok 22 | 1.18.34 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/goods/GoodsVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.goods; 2 | 3 | /** 4 | *

5 | * 6 | * @author leone 7 | * @since 2019-02-22 8 | **/ 9 | public class GoodsVO { 10 | 11 | private Long goodsId; 12 | 13 | private String name; 14 | 15 | private Integer price; 16 | 17 | private String picture; 18 | 19 | public Long getGoodsId() { 20 | return goodsId; 21 | } 22 | 23 | public void setGoodsId(Long goodsId) { 24 | this.goodsId = goodsId; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public Integer getPrice() { 36 | return price; 37 | } 38 | 39 | public void setPrice(Integer price) { 40 | this.price = price; 41 | } 42 | 43 | public String getPicture() { 44 | return picture; 45 | } 46 | 47 | public void setPicture(String picture) { 48 | this.picture = picture; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/order/OrderVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.order; 2 | 3 | import com.leone.cloud.common.beans.order.item.OrderItemVO; 4 | 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | /** 9 | *

10 | * 11 | * @author leone 12 | * @since 2019-01-22 13 | **/ 14 | public class OrderVO { 15 | 16 | private Long orderId; 17 | 18 | private Long userId; 19 | 20 | private Integer totalAmount; 21 | 22 | private String remark; 23 | 24 | private String tradeNo; 25 | 26 | private Date createTime; 27 | 28 | private Date payTime; 29 | 30 | private String userAccount; 31 | 32 | private Integer userAge; 33 | 34 | private String userDescription; 35 | 36 | private List orderItemList; 37 | 38 | public List getOrderItemList() { 39 | return orderItemList; 40 | } 41 | 42 | public void setOrderItemList(List orderItemList) { 43 | this.orderItemList = orderItemList; 44 | } 45 | 46 | public Long getOrderId() { 47 | return orderId; 48 | } 49 | 50 | public void setOrderId(Long orderId) { 51 | this.orderId = orderId; 52 | } 53 | 54 | public Long getUserId() { 55 | return userId; 56 | } 57 | 58 | public void setUserId(Long userId) { 59 | this.userId = userId; 60 | } 61 | 62 | public Integer getTotalAmount() { 63 | return totalAmount; 64 | } 65 | 66 | public void setTotalAmount(Integer totalAmount) { 67 | this.totalAmount = totalAmount; 68 | } 69 | 70 | public String getRemark() { 71 | return remark; 72 | } 73 | 74 | public void setRemark(String remark) { 75 | this.remark = remark; 76 | } 77 | 78 | public String getTradeNo() { 79 | return tradeNo; 80 | } 81 | 82 | public void setTradeNo(String tradeNo) { 83 | this.tradeNo = tradeNo; 84 | } 85 | 86 | public Date getCreateTime() { 87 | return createTime; 88 | } 89 | 90 | public void setCreateTime(Date createTime) { 91 | this.createTime = createTime; 92 | } 93 | 94 | public Date getPayTime() { 95 | return payTime; 96 | } 97 | 98 | public void setPayTime(Date payTime) { 99 | this.payTime = payTime; 100 | } 101 | 102 | public String getUserAccount() { 103 | return userAccount; 104 | } 105 | 106 | public void setUserAccount(String userAccount) { 107 | this.userAccount = userAccount; 108 | } 109 | 110 | public Integer getUserAge() { 111 | return userAge; 112 | } 113 | 114 | public void setUserAge(Integer userAge) { 115 | this.userAge = userAge; 116 | } 117 | 118 | public String getUserDescription() { 119 | return userDescription; 120 | } 121 | 122 | public void setUserDescription(String userDescription) { 123 | this.userDescription = userDescription; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/order/item/OrderItemVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.order.item; 2 | 3 | /** 4 | *

5 | * 6 | * @author leone 7 | * @since 2019-02-22 8 | **/ 9 | public class OrderItemVO { 10 | 11 | private Long orderItemId; 12 | 13 | private Long goodsId; 14 | 15 | private Long orderId; 16 | 17 | private String goodsName; 18 | 19 | private Integer goodsPrice; 20 | 21 | private String goodsPicture; 22 | 23 | private Integer goodsCount; 24 | 25 | public Long getOrderItemId() { 26 | return orderItemId; 27 | } 28 | 29 | public void setOrderItemId(Long orderItemId) { 30 | this.orderItemId = orderItemId; 31 | } 32 | 33 | public Long getGoodsId() { 34 | return goodsId; 35 | } 36 | 37 | public void setGoodsId(Long goodsId) { 38 | this.goodsId = goodsId; 39 | } 40 | 41 | public Long getOrderId() { 42 | return orderId; 43 | } 44 | 45 | public void setOrderId(Long orderId) { 46 | this.orderId = orderId; 47 | } 48 | 49 | public String getGoodsName() { 50 | return goodsName; 51 | } 52 | 53 | public void setGoodsName(String goodsName) { 54 | this.goodsName = goodsName; 55 | } 56 | 57 | public Integer getGoodsPrice() { 58 | return goodsPrice; 59 | } 60 | 61 | public void setGoodsPrice(Integer goodsPrice) { 62 | this.goodsPrice = goodsPrice; 63 | } 64 | 65 | public String getGoodsPicture() { 66 | return goodsPicture; 67 | } 68 | 69 | public void setGoodsPicture(String goodsPicture) { 70 | this.goodsPicture = goodsPicture; 71 | } 72 | 73 | public Integer getGoodsCount() { 74 | return goodsCount; 75 | } 76 | 77 | public void setGoodsCount(Integer goodsCount) { 78 | this.goodsCount = goodsCount; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/user/UserAddVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.user; 2 | 3 | /** 4 | *

5 | * 6 | * @author Leone 7 | * @since 2018-11-09 8 | **/ 9 | public class UserAddVO { 10 | 11 | private String account; 12 | 13 | private String password; 14 | 15 | private String description; 16 | 17 | private Integer age; 18 | 19 | public String getAccount() { 20 | return account; 21 | } 22 | 23 | public void setAccount(String account) { 24 | this.account = account; 25 | } 26 | 27 | public String getPassword() { 28 | return password; 29 | } 30 | 31 | public void setPassword(String password) { 32 | this.password = password; 33 | } 34 | 35 | public String getDescription() { 36 | return description; 37 | } 38 | 39 | public void setDescription(String description) { 40 | this.description = description; 41 | } 42 | 43 | public Integer getAge() { 44 | return age; 45 | } 46 | 47 | public void setAge(Integer age) { 48 | this.age = age; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/user/UserEditVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.user; 2 | 3 | /** 4 | *

5 | * 6 | * @author Leone 7 | * @since 2018-11-09 8 | **/ 9 | public class UserEditVO { 10 | 11 | private Long userId; 12 | 13 | private String account; 14 | 15 | private String password; 16 | 17 | private String description; 18 | 19 | private Integer age; 20 | 21 | public Long getUserId() { 22 | return userId; 23 | } 24 | 25 | public void setUserId(Long userId) { 26 | this.userId = userId; 27 | } 28 | 29 | public String getAccount() { 30 | return account; 31 | } 32 | 33 | public void setAccount(String account) { 34 | this.account = account; 35 | } 36 | 37 | public String getPassword() { 38 | return password; 39 | } 40 | 41 | public void setPassword(String password) { 42 | this.password = password; 43 | } 44 | 45 | public String getDescription() { 46 | return description; 47 | } 48 | 49 | public void setDescription(String description) { 50 | this.description = description; 51 | } 52 | 53 | public Integer getAge() { 54 | return age; 55 | } 56 | 57 | public void setAge(Integer age) { 58 | this.age = age; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/beans/user/UserVO.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.beans.user; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | *

7 | * 8 | * @author Leone 9 | * @since 2018-11-09 10 | **/ 11 | public class UserVO { 12 | 13 | private Long userId; 14 | 15 | private String account; 16 | 17 | private Date createTime; 18 | 19 | private String description; 20 | 21 | private Integer age; 22 | 23 | 24 | public Long getUserId() { 25 | return userId; 26 | } 27 | 28 | public void setUserId(Long userId) { 29 | this.userId = userId; 30 | } 31 | 32 | public String getAccount() { 33 | return account; 34 | } 35 | 36 | public void setAccount(String account) { 37 | this.account = account; 38 | } 39 | 40 | public Date getCreateTime() { 41 | return createTime; 42 | } 43 | 44 | public void setCreateTime(Date createTime) { 45 | this.createTime = createTime; 46 | } 47 | 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | public void setDescription(String description) { 53 | this.description = description; 54 | } 55 | 56 | public Integer getAge() { 57 | return age; 58 | } 59 | 60 | public void setAge(Integer age) { 61 | this.age = age; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/entity/Goods.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | *

8 | * 9 | * @author leone 10 | * @since 2019-01-22 11 | **/ 12 | public class Goods implements Serializable { 13 | 14 | private Long goodsId; 15 | 16 | private String name; 17 | 18 | private Integer price; 19 | 20 | private String picture; 21 | 22 | private Integer stock; 23 | 24 | private Date createTime; 25 | 26 | private Boolean deleted; 27 | 28 | public Goods() { 29 | } 30 | 31 | public Goods(Long goodsId, String name, Integer price, String picture, Integer stock, Date createTime, Boolean deleted) { 32 | this.goodsId = goodsId; 33 | this.name = name; 34 | this.price = price; 35 | this.picture = picture; 36 | this.stock = stock; 37 | this.createTime = createTime; 38 | this.deleted = deleted; 39 | } 40 | 41 | public Long getGoodsId() { 42 | return goodsId; 43 | } 44 | 45 | public void setGoodsId(Long goodsId) { 46 | this.goodsId = goodsId; 47 | } 48 | 49 | public String getName() { 50 | return name; 51 | } 52 | 53 | public void setName(String name) { 54 | this.name = name; 55 | } 56 | 57 | public Integer getPrice() { 58 | return price; 59 | } 60 | 61 | public void setPrice(Integer price) { 62 | this.price = price; 63 | } 64 | 65 | public String getPicture() { 66 | return picture; 67 | } 68 | 69 | public void setPicture(String picture) { 70 | this.picture = picture; 71 | } 72 | 73 | public Integer getStock() { 74 | return stock; 75 | } 76 | 77 | public void setStock(Integer stock) { 78 | this.stock = stock; 79 | } 80 | 81 | public Date getCreateTime() { 82 | return createTime; 83 | } 84 | 85 | public void setCreateTime(Date createTime) { 86 | this.createTime = createTime; 87 | } 88 | 89 | public Boolean getDeleted() { 90 | return deleted; 91 | } 92 | 93 | public void setDeleted(Boolean deleted) { 94 | this.deleted = deleted; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/entity/Order.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.entity; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | * @author Leone 7 | * @since 2018-06-21 8 | **/ 9 | public class Order { 10 | 11 | private Long orderId; 12 | 13 | private Long userId; 14 | 15 | private Integer totalAmount; 16 | 17 | private String remark; 18 | 19 | private String tradeNo; 20 | 21 | private Date createTime; 22 | 23 | private Date payTime; 24 | 25 | private boolean deleted; 26 | 27 | public Order() { 28 | } 29 | 30 | public Order(Long orderId, Long userId, Integer totalAmount, String remark, String tradeNo, Date createTime, Date payTime, boolean deleted) { 31 | this.orderId = orderId; 32 | this.userId = userId; 33 | this.totalAmount = totalAmount; 34 | this.remark = remark; 35 | this.tradeNo = tradeNo; 36 | this.createTime = createTime; 37 | this.payTime = payTime; 38 | this.deleted = deleted; 39 | } 40 | 41 | public Long getOrderId() { 42 | return orderId; 43 | } 44 | 45 | public void setOrderId(Long orderId) { 46 | this.orderId = orderId; 47 | } 48 | 49 | public Long getUserId() { 50 | return userId; 51 | } 52 | 53 | public void setUserId(Long userId) { 54 | this.userId = userId; 55 | } 56 | 57 | public Integer getTotalAmount() { 58 | return totalAmount; 59 | } 60 | 61 | public void setTotalAmount(Integer totalAmount) { 62 | this.totalAmount = totalAmount; 63 | } 64 | 65 | public String getRemark() { 66 | return remark; 67 | } 68 | 69 | public void setRemark(String remark) { 70 | this.remark = remark; 71 | } 72 | 73 | public String getTradeNo() { 74 | return tradeNo; 75 | } 76 | 77 | public void setTradeNo(String tradeNo) { 78 | this.tradeNo = tradeNo; 79 | } 80 | 81 | public Date getCreateTime() { 82 | return createTime; 83 | } 84 | 85 | public void setCreateTime(Date createTime) { 86 | this.createTime = createTime; 87 | } 88 | 89 | public Date getPayTime() { 90 | return payTime; 91 | } 92 | 93 | public void setPayTime(Date payTime) { 94 | this.payTime = payTime; 95 | } 96 | 97 | public boolean isDeleted() { 98 | return deleted; 99 | } 100 | 101 | public void setDeleted(boolean deleted) { 102 | this.deleted = deleted; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/entity/OrderItem.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.entity; 2 | 3 | import java.util.Date; 4 | 5 | /** 6 | *

7 | * 8 | * @author leone 9 | * @since 2019-02-22 10 | **/ 11 | public class OrderItem { 12 | 13 | private Long orderItemId; 14 | 15 | private Long goodsId; 16 | 17 | private Long orderId; 18 | 19 | private String goodsName; 20 | 21 | private Integer goodsPrice; 22 | 23 | private String goodsPicture; 24 | 25 | private Integer goodsCount; 26 | 27 | private Date createTime; 28 | 29 | public OrderItem() { 30 | } 31 | 32 | public OrderItem(Long orderItemId, Long goodsId, Long orderId, String goodsName, Integer goodsPrice, String goodsPicture, Integer goodsCount, Date createTime) { 33 | this.orderItemId = orderItemId; 34 | this.goodsId = goodsId; 35 | this.orderId = orderId; 36 | this.goodsName = goodsName; 37 | this.goodsPrice = goodsPrice; 38 | this.goodsPicture = goodsPicture; 39 | this.goodsCount = goodsCount; 40 | this.createTime = createTime; 41 | } 42 | 43 | public Long getOrderItemId() { 44 | return orderItemId; 45 | } 46 | 47 | public void setOrderItemId(Long orderItemId) { 48 | this.orderItemId = orderItemId; 49 | } 50 | 51 | public Long getGoodsId() { 52 | return goodsId; 53 | } 54 | 55 | public void setGoodsId(Long goodsId) { 56 | this.goodsId = goodsId; 57 | } 58 | 59 | public Long getOrderId() { 60 | return orderId; 61 | } 62 | 63 | public void setOrderId(Long orderId) { 64 | this.orderId = orderId; 65 | } 66 | 67 | public String getGoodsName() { 68 | return goodsName; 69 | } 70 | 71 | public void setGoodsName(String goodsName) { 72 | this.goodsName = goodsName; 73 | } 74 | 75 | public Integer getGoodsPrice() { 76 | return goodsPrice; 77 | } 78 | 79 | public void setGoodsPrice(Integer goodsPrice) { 80 | this.goodsPrice = goodsPrice; 81 | } 82 | 83 | public String getGoodsPicture() { 84 | return goodsPicture; 85 | } 86 | 87 | public void setGoodsPicture(String goodsPicture) { 88 | this.goodsPicture = goodsPicture; 89 | } 90 | 91 | public Integer getGoodsCount() { 92 | return goodsCount; 93 | } 94 | 95 | public void setGoodsCount(Integer goodsCount) { 96 | this.goodsCount = goodsCount; 97 | } 98 | 99 | public Date getCreateTime() { 100 | return createTime; 101 | } 102 | 103 | public void setCreateTime(Date createTime) { 104 | this.createTime = createTime; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.entity; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | /** 7 | *

8 | * 9 | * @author Leone 10 | * @since 2017-11-09 11 | **/ 12 | public class User implements Serializable { 13 | 14 | private static final long serialVersionUID = -8654229598582165411L; 15 | 16 | private Long userId; 17 | 18 | private String account; 19 | 20 | private String password; 21 | 22 | private String description; 23 | 24 | private Integer age; 25 | 26 | private Date createTime; 27 | 28 | private boolean deleted; 29 | 30 | public User() { 31 | } 32 | 33 | @Override 34 | public User clone() throws CloneNotSupportedException { 35 | return (User) super.clone(); 36 | } 37 | 38 | public User(Long userId, String account, String password, String description, Integer age, Date createTime, Boolean deleted) { 39 | this.userId = userId; 40 | this.account = account; 41 | this.password = password; 42 | this.description = description; 43 | this.age = age; 44 | this.createTime = createTime; 45 | this.deleted = deleted; 46 | } 47 | 48 | public Long getUserId() { 49 | return userId; 50 | } 51 | 52 | public void setUserId(Long userId) { 53 | this.userId = userId; 54 | } 55 | 56 | public String getAccount() { 57 | return account; 58 | } 59 | 60 | public void setAccount(String account) { 61 | this.account = account; 62 | } 63 | 64 | public String getPassword() { 65 | return password; 66 | } 67 | 68 | public void setPassword(String password) { 69 | this.password = password; 70 | } 71 | 72 | public String getDescription() { 73 | return description; 74 | } 75 | 76 | public void setDescription(String description) { 77 | this.description = description; 78 | } 79 | 80 | public Integer getAge() { 81 | return age; 82 | } 83 | 84 | public void setAge(Integer age) { 85 | this.age = age; 86 | } 87 | 88 | public Date getCreateTime() { 89 | return createTime; 90 | } 91 | 92 | public void setCreateTime(Date createTime) { 93 | this.createTime = createTime; 94 | } 95 | 96 | public boolean isDeleted() { 97 | return deleted; 98 | } 99 | 100 | public void setDeleted(boolean deleted) { 101 | this.deleted = deleted; 102 | } 103 | } -------------------------------------------------------------------------------- /spring-cloud-common/src/main/java/com/leone/cloud/common/utils/EntityFactory.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.common.utils; 2 | 3 | import com.leone.cloud.common.entity.Order; 4 | import com.leone.cloud.common.entity.User; 5 | 6 | import java.util.*; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | *

11 | * 12 | * @author leone 13 | **/ 14 | public class EntityFactory { 15 | 16 | private static final Random random = new Random(); 17 | 18 | private static final List userList = new LinkedList<>(); 19 | 20 | private static final List orderList = new LinkedList<>(); 21 | 22 | static { 23 | for (long i = 0; i < 9; i++) { 24 | Date date = new Date(new Date().getTime() - (random.nextInt(100000) + 10000)); 25 | userList.add(new User(i, RandomValue.randomUsername(), RandomValue.randomStr(16), RandomValue.randomMessage(), RandomValue.random.nextInt(50) + 10, date, false)); 26 | orderList.add(new Order(i, i, random.nextInt(1000) + 200, "Chicken and fish", 1 + RandomValue.randomNum(15), date, date, false)); 27 | orderList.add(new Order(100 + i, i, random.nextInt(100) + 200, "some apple and orange", 1 + RandomValue.randomNum(15), date, date, false)); 28 | } 29 | } 30 | 31 | /** 32 | * 获取object数据格式数据 33 | * 34 | * @param count count 35 | * @return list 36 | */ 37 | public static List getUsers(Integer count) { 38 | List userList = new ArrayList<>(); 39 | for (long i = 0; i < count; i++) { 40 | userList.add(new User(i, RandomValue.randomUsername(), RandomValue.randomStr(16), RandomValue.randomMessage(), RandomValue.random.nextInt(50) + 10, new Date(), false)); 41 | } 42 | return userList; 43 | } 44 | 45 | /** 46 | * @return user 47 | */ 48 | public static Order getDefaultOrder() { 49 | return new Order(0L, 0L, 100, "Chicken and fish", "T109100", new Date(), new Date(), false); 50 | } 51 | 52 | /** 53 | * @return user 54 | */ 55 | public static User getDefaultUser() { 56 | return new User(0L, "James", "12345", "hello james", 18, new Date(), false); 57 | } 58 | 59 | /** 60 | * @param userId user 61 | * @return user 62 | */ 63 | public static User getUser(Long userId) { 64 | return userList.stream().filter(e -> e.getUserId().equals(userId)).collect(Collectors.toList()).get(0); 65 | } 66 | 67 | /** 68 | * @param userId userId 69 | */ 70 | public static void remove(Long userId) { 71 | userList.removeIf(next -> next.getUserId().equals(userId)); 72 | } 73 | 74 | 75 | /** 76 | * @param userId user 77 | * @return list 78 | */ 79 | public static List getOrderList(Long userId) { 80 | return orderList.stream().filter(e -> e.getUserId().equals(userId)).collect(Collectors.toList()); 81 | } 82 | 83 | 84 | /** 85 | * @param orderId orderId 86 | * @return order 87 | */ 88 | public static Order getOrder(Long orderId) { 89 | try { 90 | Thread.sleep(99); 91 | } catch (InterruptedException e) { 92 | throw new RuntimeException(e); 93 | } 94 | return orderList.stream().filter(e -> e.getUserId().equals(orderId)).collect(Collectors.toList()).get(0); 95 | } 96 | 97 | 98 | } -------------------------------------------------------------------------------- /spring-cloud-config-apollo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.leone.cloud 8 | spring-cloud-examples 9 | 2.0.0.RELEASE 10 | 11 | 12 | spring-cloud-config-apollo 13 | 14 | 15 | 17 16 | 17 17 | UTF-8 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.cloud 24 | spring-cloud-dependencies 25 | 2023.0.3 26 | pom 27 | import 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-dependencies 32 | 3.3.5 33 | pom 34 | import 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-web 44 | 45 | 46 | 47 | 48 | com.ctrip.framework.apollo 49 | apollo-client 50 | 2.3.0 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /spring-cloud-config-apollo/src/main/java/com/leone/cloud/apollo/ApolloApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.apollo; 2 | 3 | import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | /** 8 | *

9 | * 10 | * @author leone 11 | * @since 2024-12-08 12 | **/ 13 | @EnableApolloConfig 14 | @SpringBootApplication 15 | public class ApolloApplication { 16 | public static void main(String[] args) { 17 | SpringApplication.run(ApolloApplication.class, args); 18 | } 19 | } -------------------------------------------------------------------------------- /spring-cloud-config-apollo/src/main/java/com/leone/cloud/apollo/config/ApolloConfigService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.apollo.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.scheduling.annotation.EnableScheduling; 5 | import org.springframework.scheduling.annotation.Scheduled; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | *

10 | * 11 | * @author leone 12 | * @since 2024-12-08 13 | **/ 14 | @Component 15 | @EnableScheduling 16 | public class ApolloConfigService { 17 | 18 | @Value("${name:defName}") 19 | private String name; 20 | 21 | @Scheduled(cron = "0/5 * * * * ?") 22 | public void pullConfig() { 23 | System.out.println("name: " + name); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /spring-cloud-config-apollo/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8081 2 | 3 | # 阿波罗配置 4 | env=LOCAL 5 | app.id=123456 6 | apollo.meta=http://localhost:8080 7 | 8 | 9 | -------------------------------------------------------------------------------- /spring-cloud-config-client/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-config-client 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-dependencies 24 | 2023.0.3 25 | pom 26 | import 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-dependencies 31 | 3.3.5 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-web 43 | 44 | 45 | 46 | org.springframework.cloud 47 | spring-cloud-starter-config 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-actuator 53 | 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-starter-netflix-eureka-client 58 | 59 | 60 | 61 | org.springframework.cloud 62 | spring-cloud-starter-bootstrap 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | org.apache.maven.plugins 71 | maven-compiler-plugin 72 | 3.8.0 73 | 74 | 17 75 | 17 76 | UTF-8 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /spring-cloud-config-client/src/main/java/com/leone/cloud/config/ConfigClientApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | /** 8 | * @author Leone 9 | * @since 2018-01-23 10 | **/ 11 | @EnableDiscoveryClient 12 | @SpringBootApplication 13 | public class ConfigClientApplication { 14 | public static void main(String[] args) { 15 | SpringApplication.run(ConfigClientApplication.class, args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-cloud-config-client/src/main/java/com/leone/cloud/config/controller/ConfigController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config.controller; 2 | 3 | 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.cloud.context.config.annotation.RefreshScope; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * @author Leone 14 | * @since 2018-01-23 15 | **/ 16 | @RefreshScope 17 | @RestController 18 | public class ConfigController { 19 | 20 | @Value("${profile}") 21 | private String profile; 22 | 23 | @Value("${name}") 24 | private String name; 25 | 26 | @Value("${filename}") 27 | private String filename; 28 | 29 | @Value("${level}") 30 | private String level; 31 | 32 | @GetMapping("/env") 33 | public Map env() { 34 | Map map = new HashMap<>(); 35 | map.put("profile", profile); 36 | map.put("level", level); 37 | map.put("filename", filename); 38 | map.put("name", name); 39 | return map; 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /spring-cloud-config-client/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9100 3 | 4 | eureka: 5 | client: 6 | service-url: 7 | defaultZone: http://localhost:8761/eureka 8 | 9 | spring: 10 | application: 11 | name: mc-config-client 12 | 13 | # 自定义默认属性 14 | # name: defaultName 15 | # profile: defaultProfile 16 | # level: defaultLevel 17 | 18 | #spring: 19 | # rabbitmq: 20 | # host: localhost 21 | # port: 5672 22 | # username: cloud 23 | # password: xxxx 24 | # virtual-host: /mc 25 | # publisher-confirms: true 26 | -------------------------------------------------------------------------------- /spring-cloud-config-client/src/main/resources/bootstrap.yml: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | spring: 4 | profiles: pro 5 | cloud: 6 | config: 7 | # 对应config server中配置文件的 {label} 8 | label: master 9 | # 访问config server的地址 10 | uri: http://localhost:8080 11 | # 对应config server中配置文件的 {profile} 12 | profile: test 13 | # discovery: 14 | # 表示使用服务发现组件中提供的Config Server,默认是false 15 | # 开启通过服务发现组件访问Config Server的功能 16 | # enabled: true 17 | #指定Config Server在服务发现组件中的serviceId 18 | # service-id: mc-config-server 19 | # enabled: true 20 | 21 | --- 22 | spring: 23 | profiles: test 24 | cloud: 25 | config: 26 | label: master 27 | uri: http://localhost:8080 28 | profile: test 29 | 30 | 31 | --- 32 | spring: 33 | config: 34 | activate: 35 | on-profile: pro 36 | -------------------------------------------------------------------------------- /spring-cloud-config-server-bus/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-config-server-bus 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-dependencies 24 | 2023.0.3 25 | pom 26 | import 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-dependencies 31 | 3.3.5 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.cloud 41 | spring-cloud-config-server 42 | 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-netflix-eureka-client 47 | 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-actuator 52 | 53 | 54 | 55 | org.springframework.cloud 56 | spring-cloud-starter-bus-amqp 57 | 58 | 59 | 60 | org.springframework.cloud 61 | spring-cloud-starter-netflix-hystrix 62 | 2.2.10.RELEASE 63 | 64 | 65 | 66 | com.leone.cloud 67 | spring-cloud-common 68 | 2.0.0.RELEASE 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-compiler-plugin 78 | 3.8.0 79 | 80 | 17 81 | 17 82 | UTF-8 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 2.0.3.RELEASE 90 | 91 | 92 | ZIP 93 | 94 | 95 | 96 | 97 | repackage 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /spring-cloud-config-server-bus/src/main/java/com/leone/cloud/config/ConfigServerBusApp.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.config.server.EnableConfigServer; 7 | 8 | /** 9 | * @author Leone 10 | * @since 2018-2-23 11 | **/ 12 | @EnableConfigServer 13 | @EnableDiscoveryClient 14 | @SpringBootApplication 15 | public class ConfigServerBusApp { 16 | public static void main(String[] args) { 17 | SpringApplication.run(ConfigServerBusApp.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-cloud-config-server-bus/src/main/java/com/leone/cloud/config/controller/ConfigController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config.controller; 2 | 3 | 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.HashMap; 12 | import java.util.Map; 13 | 14 | /** 15 | * @author Leone 16 | * @since 2018-1-25 17 | **/ 18 | @Slf4j 19 | @RestController 20 | public class ConfigController { 21 | 22 | @Value("${profile}") 23 | private String profile; 24 | 25 | @Value("${name}") 26 | private String name; 27 | 28 | @Value("${level}") 29 | private String level; 30 | 31 | @RequestMapping(value = "/profile", method = RequestMethod.GET) 32 | public String profile() { 33 | return profile; 34 | } 35 | 36 | @GetMapping("/env") 37 | public Map env() { 38 | Map map = new HashMap<>(); 39 | map.put("profile", profile); 40 | map.put("name", name); 41 | map.put("level", level); 42 | return map; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /spring-cloud-config-server-bus/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9005 3 | #自定义属性 4 | name: andy 5 | profile: test 6 | level: default 7 | 8 | eureka: 9 | client: 10 | service-url: 11 | defaultZone: http://localhost:8761/eureka 12 | 13 | spring: 14 | application: 15 | name: spring-cloud-config-server-bus 16 | cloud: 17 | config: 18 | server: 19 | git: 20 | uri: https://github.com/fooelliot/config-repo.git 21 | basedir: D:\tmp\config 22 | rabbitmq: 23 | host: localhost 24 | port: 5672 25 | username: cloud 26 | password: xxxx 27 | virtual-host: /cloud 28 | 29 | management: 30 | endpoints: 31 | web: 32 | exposure: 33 | include: "*" 34 | -------------------------------------------------------------------------------- /spring-cloud-config-server/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-config-server 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-dependencies 24 | 2023.0.3 25 | pom 26 | import 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-dependencies 31 | 3.3.5 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.cloud 41 | spring-cloud-config-server 42 | 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-netflix-eureka-client 47 | 48 | 49 | 50 | 51 | 52 | 53 | org.apache.maven.plugins 54 | maven-compiler-plugin 55 | 3.8.0 56 | 57 | 17 58 | 17 59 | UTF-8 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/java/com/leone/cloud/config/ConfigServerApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.servlet.ServletComponentScan; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.cloud.config.server.EnableConfigServer; 8 | 9 | 10 | /** 11 | * @author Leone 12 | * @since 2017-12-07 13 | **/ 14 | @EnableConfigServer 15 | @ServletComponentScan 16 | @EnableDiscoveryClient 17 | @SpringBootApplication 18 | public class ConfigServerApplication { 19 | public static void main(String[] args) { 20 | SpringApplication.run(ConfigServerApplication.class, args); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/java/com/leone/cloud/config/filter/CustomerRequestWrapper.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config.filter; 2 | 3 | import jakarta.servlet.ReadListener; 4 | import jakarta.servlet.ServletInputStream; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import jakarta.servlet.http.HttpServletRequestWrapper; 7 | 8 | import java.io.ByteArrayInputStream; 9 | import java.io.IOException; 10 | 11 | /** 12 | *

13 | * 14 | * @author leone 15 | * @since 2019-03-30 16 | **/ 17 | public class CustomerRequestWrapper extends HttpServletRequestWrapper { 18 | 19 | public CustomerRequestWrapper(HttpServletRequest request) { 20 | super(request); 21 | } 22 | 23 | @Override 24 | public ServletInputStream getInputStream() throws IOException { 25 | byte[] bytes = new byte[0]; 26 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); 27 | 28 | return new ServletInputStream() { 29 | @Override 30 | public boolean isFinished() { 31 | return byteArrayInputStream.read() == -1; 32 | } 33 | 34 | @Override 35 | public boolean isReady() { 36 | return false; 37 | } 38 | 39 | @Override 40 | public void setReadListener(ReadListener readListener) { 41 | 42 | } 43 | 44 | @Override 45 | public int read() throws IOException { 46 | return byteArrayInputStream.read(); 47 | } 48 | }; 49 | } 50 | } -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/java/com/leone/cloud/config/filter/WebHookFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.config.filter; 2 | 3 | import jakarta.servlet.*; 4 | import jakarta.servlet.annotation.WebFilter; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import org.springframework.core.annotation.Order; 7 | 8 | import java.io.IOException; 9 | 10 | /** 11 | *

12 | * 13 | * @author leone 14 | * @since 2019-03-30 15 | **/ 16 | @Order(1) 17 | @WebFilter(filterName = "webHookFilter", urlPatterns = "/*") 18 | public class WebHookFilter implements Filter { 19 | 20 | @Override 21 | public void init(FilterConfig filterConfig) throws ServletException { 22 | } 23 | 24 | @Override 25 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 26 | HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest; 27 | String url = httpServletRequest.getRequestURI(); 28 | // 只过滤/actuator/bus-refresh请求 29 | if (!url.endsWith("/bus-refresh")) { 30 | filterChain.doFilter(servletRequest, servletResponse); 31 | return; 32 | } 33 | // 使用HttpServletRequest包装原始请求达到修改post请求中body内容的目的 34 | CustomerRequestWrapper requestWrapper = new CustomerRequestWrapper(httpServletRequest); 35 | filterChain.doFilter(requestWrapper, servletResponse); 36 | } 37 | 38 | @Override 39 | public void destroy() { 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: mc-config-server 4 | cloud: 5 | config: 6 | server: 7 | git: 8 | uri: https://gitee.com/janlle/config_repo.git 9 | # 访问git仓库的用户名(非私有库可以不用配置) 10 | username: janlle 11 | # 访问git仓库的密码(非私有库可以不用配置) 12 | password: Rlgitee90.> 13 | search-paths: / 14 | # 在启动的时候就会下载 15 | clone-on-start: true 16 | # git 分支 17 | default-label: master 18 | 19 | eureka: 20 | client: 21 | service-url: 22 | defaultZone: http://localhost:8761/eureka 23 | 24 | -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/resources/application.yml1.bak: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9000 3 | spring: 4 | application: 5 | name: spring-cloud-config-server 6 | cloud: 7 | config: 8 | server: 9 | git: 10 | uri: https://gitee.com/thethink/config_repo 11 | username: xxx 12 | password: xxx -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/resources/application.yml2.bak: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9000 3 | spring: 4 | application: 5 | name: spring-cloud-config-server 6 | cloud: 7 | config: 8 | server: 9 | git: 10 | uri: https://gitee.com/janlle/{application} -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/resources/application.yml3.bak: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9000 3 | spring: 4 | cloud: 5 | config: 6 | server: 7 | git: 8 | uri: https://gitee.com/janlle/config_repo 9 | repos: 10 | simple: https://gitee.com/janlle/simple 11 | special: 12 | pattern: special*/dev*,*special*/test* 13 | url: https://gitee.com/janlle/special 14 | 15 | -------------------------------------------------------------------------------- /spring-cloud-config-server/src/main/resources/application.yml4.bak: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9000 3 | spring: 4 | application: 5 | name: springCloud-config-server 6 | cloud: 7 | config: 8 | server: 9 | git: 10 | uri: https://gitee.com/janlle/config_repo 11 | search-paths: 12 | - def 13 | - test 14 | clone-on-start: true #在启动的时候就会下载 -------------------------------------------------------------------------------- /spring-cloud-eureka/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | spring-cloud-eureka 5 | 6 | 7 | com.leone.cloud 8 | spring-cloud-examples 9 | 2.0.0.RELEASE 10 | 11 | 12 | 13 | 17 14 | 17 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | org.springframework.cloud 40 | spring-cloud-starter-netflix-eureka-server 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /spring-cloud-eureka/src/main/java/com/leone/cloud/eureka/EurekaApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.eureka; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | /** 8 | *

9 | * 10 | * @author Leone 11 | * @since 2017-10-10 12 | **/ 13 | @EnableEurekaServer 14 | @SpringBootApplication 15 | public class EurekaApplication { 16 | public static void main(String[] args) { 17 | SpringApplication.run(EurekaApplication.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-cloud-eureka/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8761 3 | 4 | eureka: 5 | client: 6 | # 是否将自己注册到Eureka服务中,本身就是所有无需注册 7 | register-with-eureka: false 8 | # 是否从Eureka中获取注册信息 9 | fetch-registry: false 10 | 11 | -------------------------------------------------------------------------------- /spring-cloud-gateway/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-gateway 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.cloud 41 | spring-cloud-starter-netflix-eureka-client 42 | 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-gateway 47 | 4.1.5 48 | 49 | 50 | 51 | io.netty 52 | netty-resolver-dns-native-macos 53 | 4.1.114.Final 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-compiler-plugin 63 | 3.8.0 64 | 65 | 17 66 | 17 67 | UTF-8 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /spring-cloud-gateway/src/main/java/com/leone/cloud/gateway/GatewayApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.gateway; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | /** 8 | * @author leone 9 | * @since 2018-06-21 10 | **/ 11 | @EnableDiscoveryClient 12 | @SpringBootApplication 13 | public class GatewayApplication { 14 | public static void main(String[] args) { 15 | SpringApplication.run(GatewayApplication.class, args); 16 | } 17 | } -------------------------------------------------------------------------------- /spring-cloud-gateway/src/main/java/com/leone/cloud/gateway/config/GatewayConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.gateway.config; 2 | 3 | import org.springframework.cloud.gateway.route.RouteLocator; 4 | import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | /** 9 | *

10 | * 11 | * @author leone 12 | * @since 2019-01-23 13 | **/ 14 | //@Configuration 15 | public class GatewayConfiguration { 16 | 17 | @Bean 18 | public RouteLocator serviceRoute(RouteLocatorBuilder builder) { 19 | return builder 20 | .routes() 21 | .route(r -> r.path("/order/**") 22 | .filters(f -> f.addRequestHeader("jack", "hello")) 23 | .uri("http://127.0.0.1:9002")) 24 | .build(); 25 | } 26 | 27 | /** 28 | * 通过代码的方式配置路由,在浏览器输入http://localhost:9999/about 将跳转到百度首页 29 | */ 30 | @Bean 31 | public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { 32 | return builder 33 | .routes() 34 | .route(r -> r.path("/about") 35 | .filters(f -> f.addRequestHeader("token", "hello")) 36 | .uri("http://baidu.com")) 37 | .build(); 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /spring-cloud-gateway/src/main/java/com/leone/cloud/gateway/filter/PreGatewayFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.gateway.filter; 2 | 3 | /** 4 | *

5 | * 6 | * @author leone 7 | * @since 2019-01-23 8 | **/ 9 | public class PreGatewayFilter { 10 | } 11 | -------------------------------------------------------------------------------- /spring-cloud-gateway/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9999 3 | 4 | eureka: 5 | client: 6 | service-url: 7 | defaultZone: http://localhost:8761/eureka 8 | 9 | spring: 10 | application: 11 | name: mc-gateway 12 | cloud: 13 | gateway: 14 | locator: 15 | # 是否从注册中心读取服务 16 | enabled: true 17 | routes: 18 | - id: mc-order 19 | uri: http://mc-order 20 | predicates: 21 | - Header=X-Request-Id, \d+ 22 | - Path=/order/** 23 | - id: mc-user 24 | uri: lb://mc-user 25 | # uri: http://localhost:9000 26 | predicates: 27 | - Path=/user/** 28 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-hystrix-feign 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-web 42 | 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-netflix-eureka-client 47 | 48 | 49 | 50 | org.springframework.cloud 51 | spring-cloud-starter-openfeign 52 | 2.0.2.RELEASE 53 | 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-starter-netflix-hystrix 58 | 2.2.10.RELEASE 59 | 60 | 61 | 62 | org.springframework.boot 63 | spring-boot-starter-actuator 64 | 65 | 66 | 67 | com.leone.cloud 68 | spring-cloud-common 69 | 2.0.0.RELEASE 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.apache.maven.plugins 78 | maven-compiler-plugin 79 | 3.8.0 80 | 81 | 17 82 | 17 83 | UTF-8 84 | 85 | 86 | 87 | 88 | org.springframework.boot 89 | spring-boot-maven-plugin 90 | 2.0.3.RELEASE 91 | 92 | 93 | ZIP 94 | 95 | 96 | 97 | 98 | repackage 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/java/com/leone/cloud/hystrix/HystrixFeignApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.hystrix; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 5 | import org.springframework.cloud.netflix.hystrix.EnableHystrix; 6 | import org.springframework.cloud.openfeign.EnableFeignClients; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | import java.util.Random; 10 | 11 | /** 12 | *

13 | * 14 | * @author Leone 15 | * @since 2018-02-11 16 | **/ 17 | @EnableHystrix 18 | @EnableFeignClients 19 | @EnableDiscoveryClient 20 | public class HystrixFeignApplication { 21 | 22 | public static void main(String[] args) { 23 | SpringApplication.run(HystrixFeignApplication.class, args); 24 | } 25 | 26 | @Bean 27 | public Random random() { 28 | return new Random(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/java/com/leone/cloud/hystrix/controller/HystrixController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.hystrix.controller; 2 | 3 | import com.leone.cloud.common.entity.User; 4 | import com.leone.cloud.hystrix.feign.UserFeign; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | /** 13 | * @author Leone 14 | * @since 2017-12-22 15 | **/ 16 | @Slf4j 17 | @RestController 18 | @RequestMapping("/hystrix") 19 | public class HystrixController { 20 | 21 | @Autowired 22 | private UserFeign userFeign; 23 | 24 | @GetMapping("/user") 25 | public User user(@RequestParam Long userId) { 26 | return userFeign.find(userId); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/java/com/leone/cloud/hystrix/fallback/UserFeignFallback.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.hystrix.fallback; 2 | 3 | import com.leone.cloud.common.beans.user.UserAddVO; 4 | import com.leone.cloud.common.beans.user.UserEditVO; 5 | import com.leone.cloud.common.beans.user.UserVO; 6 | import com.leone.cloud.common.entity.User; 7 | import com.leone.cloud.hystrix.feign.UserFeign; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.multipart.MultipartFile; 11 | 12 | import java.util.*; 13 | 14 | /** 15 | *

16 | * 17 | * @author leone 18 | * @since 2018-02-13 19 | **/ 20 | @Slf4j 21 | @Component 22 | public class UserFeignFallback implements UserFeign { 23 | 24 | @Override 25 | public User find(Long id) { 26 | log.info("UserFeignFallback: {} find", id); 27 | return new User(1L, "default", "123456", "good man", 18, new Date(), false); 28 | } 29 | 30 | @Override 31 | public List list() { 32 | log.info("UserFeignFallback list"); 33 | return Collections.singletonList(new User(1L, "default", "123456", "good man", 18, new Date(), false)); 34 | } 35 | 36 | @Override 37 | public UserVO update(UserEditVO user) { 38 | log.info("UserFeignFallback update"); 39 | return new UserVO(); 40 | } 41 | 42 | @Override 43 | public UserVO save(UserAddVO user) { 44 | log.info("UserFeignFallback save"); 45 | return new UserVO(); 46 | } 47 | 48 | @Override 49 | public void delete(Map query) { 50 | log.info("UserFeignFallback delete"); 51 | } 52 | 53 | @Override 54 | public String upload(MultipartFile file) { 55 | log.info("UserFeignFallback"); 56 | return "fallback"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/java/com/leone/cloud/hystrix/fallback/UserFeignFallbackFactory.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.hystrix.fallback; 2 | 3 | import com.leone.cloud.common.beans.user.UserAddVO; 4 | import com.leone.cloud.common.beans.user.UserEditVO; 5 | import com.leone.cloud.common.beans.user.UserVO; 6 | import com.leone.cloud.common.entity.User; 7 | import com.leone.cloud.hystrix.feign.UserFeign; 8 | import feign.hystrix.FallbackFactory; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.web.multipart.MultipartFile; 12 | 13 | import java.util.Collections; 14 | import java.util.Date; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | /** 19 | *

20 | * 21 | * @author leone 22 | * @since 2018-02-13 23 | **/ 24 | @Slf4j 25 | @Component 26 | public class UserFeignFallbackFactory implements FallbackFactory { 27 | 28 | @Override 29 | public UserFeign create(Throwable throwable) { 30 | return new UserFeign() { 31 | @Override 32 | public User find(Long id) { 33 | log.info("UserFeignFallback: {} find", id); 34 | return new User(100L, "defaultFactory", "123456", "good man", 28, new Date(), false); 35 | } 36 | 37 | @Override 38 | public List list() { 39 | log.info("UserFeignFallback list"); 40 | return Collections.singletonList(new User(100L, "defaultFactory", "123456", "good man", 28, new Date(), false)); 41 | } 42 | 43 | @Override 44 | public UserVO update(UserEditVO user) { 45 | log.info("UserFeignFallback update"); 46 | return new UserVO(); 47 | } 48 | 49 | @Override 50 | public UserVO save(UserAddVO user) { 51 | log.info("UserFeignFallback save"); 52 | return new UserVO(); 53 | } 54 | 55 | @Override 56 | public void delete(Map query) { 57 | log.info("UserFeignFallback delete"); 58 | } 59 | 60 | @Override 61 | public String upload(MultipartFile file) { 62 | log.info("UserFeignFallback"); 63 | return "fallback"; 64 | } 65 | }; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/java/com/leone/cloud/hystrix/feign/UserFeign.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.hystrix.feign; 2 | 3 | import com.leone.cloud.common.beans.user.UserAddVO; 4 | import com.leone.cloud.common.beans.user.UserEditVO; 5 | import com.leone.cloud.common.beans.user.UserVO; 6 | import com.leone.cloud.common.entity.User; 7 | import com.leone.cloud.hystrix.fallback.UserFeignFallbackFactory; 8 | import feign.QueryMap; 9 | import org.springframework.cloud.openfeign.FeignClient; 10 | import org.springframework.web.bind.annotation.*; 11 | import org.springframework.web.multipart.MultipartFile; 12 | 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | /** 17 | *

@FeignClient value 值是上游服务的 spring.application.name 18 | * 19 | * @author Leone 20 | * @since 2018-02-16 21 | **/ 22 | @FeignClient(value = "mc-user", /*url = "http://127.0.0.1/user",*/ /*fallback = UserFeignFallback.class*/fallbackFactory = UserFeignFallbackFactory.class) 23 | public interface UserFeign { 24 | 25 | @GetMapping("/user/{userId}") 26 | User find(@PathVariable("userId") Long userId); 27 | 28 | @GetMapping("/user/list") 29 | List list(); 30 | 31 | @PutMapping("/user") 32 | UserVO update(@RequestBody UserEditVO user); 33 | 34 | @PostMapping("/user") 35 | UserVO save(@RequestBody UserAddVO user); 36 | 37 | @DeleteMapping("/user") 38 | void delete(@QueryMap Map query); 39 | 40 | @PostMapping("/user/upload") 41 | String upload(MultipartFile file); 42 | 43 | } 44 | 45 | 46 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8109 3 | 4 | spring: 5 | application: 6 | name: mc-hystrix 7 | eureka: 8 | client: 9 | serviceUrl: 10 | defaultZone: http://localhost:8761/eureka 11 | instance: 12 | appname: hystrix-service 13 | 14 | # 新版本中需要独立设置开启feign对hystrix的支持,旧版本中默认开启对hystrix支持 15 | feign: 16 | hystrix: 17 | enabled: true 18 | 19 | # spring boot 2.x actuator 的配置 20 | management: 21 | endpoints: 22 | web: 23 | exposure: 24 | include: "*" 25 | basePath: /monitor 26 | endpoint: 27 | health: 28 | showDetails: always 29 | 30 | 31 | # 配置hystrix 32 | hystrix: 33 | threadpool: 34 | default: 35 | coreSize: 10 #线程池核心线程数 36 | metrics: 37 | polling-interval-ms: 2000 38 | enabled: true 39 | command: 40 | # IService#hello(): 设置某一个接口 default: 设置全部接口 41 | default: 42 | execution: 43 | timeout: 44 | # 关闭熔断功能 45 | enabled: true 46 | isolation: 47 | thread: 48 | timeoutInMilliseconds: 2000 # 超时时间 49 | circuitBreaker: 50 | requestVolumeThreshold: 3 # 当在配置时间窗口内达到此数量后,进行短路。默认20个 51 | sleepWindowInMilliseconds: 5 # 短路多久以后开始尝试是否恢复,默认5s 52 | errorThresholdPercentage: 50% # 出错百分比阈值,当达到此阈值后,开始短路。默认50% 53 | 54 | -------------------------------------------------------------------------------- /spring-cloud-hystrix-feign/src/main/resources/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janlle/spring-cloud-examples/8f0e0dbb7b9c95dda7920c569657640d25387c18/spring-cloud-hystrix-feign/src/main/resources/config.properties -------------------------------------------------------------------------------- /spring-cloud-order/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-order 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | UTF-8 17 | 18 | 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-dependencies 24 | 2023.0.3 25 | pom 26 | import 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-dependencies 31 | 3.3.5 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.cloud 41 | spring-cloud-starter-netflix-eureka-client 42 | 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-netflix-hystrix 47 | 2.2.10.RELEASE 48 | 49 | 50 | 51 | 52 | org.springframework.cloud 53 | spring-cloud-starter-netflix-hystrix-dashboard 54 | 2.0.1.RELEASE 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-web 60 | 61 | 62 | 63 | org.projectlombok 64 | lombok 65 | 66 | 67 | 68 | com.leone.cloud 69 | spring-cloud-common 70 | 2.0.0.RELEASE 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-compiler-plugin 80 | 3.8.0 81 | 82 | 17 83 | 17 84 | UTF-8 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/OrderApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.hystrix.EnableHystrix; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.web.client.RestTemplate; 9 | 10 | 11 | /** 12 | *

下游服务 13 | * 14 | * @author Leone 15 | * @since 2018-03-10 16 | **/ 17 | // @EnableHystrixDashboard 18 | // @EnableHystrix 19 | @SpringBootApplication 20 | @EnableDiscoveryClient 21 | public class OrderApplication { 22 | public static void main(String[] args) { 23 | SpringApplication.run(OrderApplication.class, args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/config/HttpClientConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.config; 2 | 3 | import com.leone.cloud.order.service.UserService; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.web.client.RestClient; 7 | import org.springframework.web.client.support.RestClientAdapter; 8 | import org.springframework.web.service.invoker.HttpServiceProxyFactory; 9 | 10 | @Configuration 11 | public class HttpClientConfig { 12 | 13 | @Bean 14 | RestClient.Builder restClientBuilder() { 15 | return RestClient.builder(); 16 | } 17 | 18 | @Bean 19 | public UserService helloClient(RestClient.Builder restClientBuilder) { 20 | return HttpServiceProxyFactory 21 | .builder() 22 | .exchangeAdapter( 23 | RestClientAdapter.create( 24 | restClientBuilder.baseUrl("http://localhost:8001").build() 25 | ) 26 | ) 27 | .build().createClient(UserService.class); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/config/HystrixConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.config; 2 | 3 | 4 | import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet; 5 | import org.springframework.boot.web.servlet.ServletRegistrationBean; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | /** 10 | *

11 | * 12 | * @author leone 13 | * @since 2018-12-22 14 | **/ 15 | // @Configuration 16 | public class HystrixConfig { 17 | 18 | @Bean 19 | public HystrixMetricsStreamServlet hystrixMetricsStreamServlet() { 20 | return new HystrixMetricsStreamServlet(); 21 | } 22 | 23 | @Bean 24 | public ServletRegistrationBean registration(HystrixMetricsStreamServlet servlet) { 25 | ServletRegistrationBean registrationBean = new ServletRegistrationBean(); 26 | // registrationBean.setServlet(servlet); 27 | // 是否启用该registrationBean 28 | registrationBean.setEnabled(true); 29 | registrationBean.addUrlMappings("/hystrix.stream"); 30 | return registrationBean; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/config/LoadBalancerConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.config; 2 | 3 | import org.springframework.cloud.client.ServiceInstance; 4 | import org.springframework.cloud.client.loadbalancer.LoadBalancerRequestTransformer; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.HttpHeaders; 8 | import org.springframework.http.HttpRequest; 9 | import org.springframework.http.client.support.HttpRequestWrapper; 10 | 11 | /** 12 | *

13 | * 14 | * @author leone 15 | * @since 2024-11-05 16 | **/ 17 | @Configuration 18 | public class LoadBalancerConfig { 19 | @Bean 20 | public LoadBalancerRequestTransformer transformer() { 21 | return new LoadBalancerRequestTransformer() { 22 | @Override 23 | public HttpRequest transformRequest(HttpRequest request, ServiceInstance instance) { 24 | return new HttpRequestWrapper(request) { 25 | @Override 26 | public HttpHeaders getHeaders() { 27 | HttpHeaders headers = new HttpHeaders(); 28 | headers.putAll(super.getHeaders()); 29 | headers.add("X-InstanceId", instance.getInstanceId()); 30 | return headers; 31 | } 32 | }; 33 | } 34 | }; 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/config/RestTemplateConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 8 | import org.springframework.web.client.RestTemplate; 9 | 10 | /** 11 | *

12 | * 13 | * @author leone 14 | * @since 2024-11-05 15 | **/ 16 | @Configuration 17 | public class RestTemplateConfig { 18 | 19 | @Bean 20 | @ConfigurationProperties(prefix = "rest.template.config") 21 | public HttpComponentsClientHttpRequestFactory customHttpRequestFactory() { 22 | return new HttpComponentsClientHttpRequestFactory(); 23 | } 24 | 25 | @Bean 26 | @LoadBalanced 27 | public RestTemplate restTemplate() { 28 | return new RestTemplate(customHttpRequestFactory()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/controller/HystrixController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.controller; 2 | 3 | import com.leone.cloud.common.entity.Order; 4 | import com.leone.cloud.common.entity.User; 5 | import com.leone.cloud.order.service.OrderService; 6 | import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; 7 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 8 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import java.util.Random; 14 | 15 | /** 16 | * @author leone 17 | * @since 2017-12-22 18 | **/ 19 | @Slf4j 20 | @RestController 21 | @RequestMapping("/hystrix") 22 | @DefaultProperties(defaultFallback = "defaultFallback") 23 | public class HystrixController { 24 | 25 | private final Random random = new Random(); 26 | 27 | @Autowired 28 | private OrderService orderService; 29 | 30 | 31 | @GetMapping("/order/{orderId}") 32 | public Order findOne(@PathVariable("orderId") Long orderId) { 33 | return orderService.findOne(orderId); 34 | } 35 | 36 | @HystrixCommand( 37 | fallbackMethod = "testFallback", 38 | threadPoolProperties = { 39 | //10个核心线程池,超过20个的队列外的请求被拒绝; 当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务 40 | @HystrixProperty(name = "coreSize", value = "10"), 41 | @HystrixProperty(name = "maxQueueSize", value = "100"), 42 | @HystrixProperty(name = "queueSizeRejectionThreshold", value = "20")}, 43 | commandProperties = { 44 | @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"), //命令执行超时时间 45 | @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"), //若干10s一个窗口内失败三次, 则达到触发熔断的最少请求量 46 | @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "30000") //断路30s后尝试执行, 默认为5s 47 | }) 48 | @GetMapping("/user/test") 49 | public String test() throws Exception { 50 | Thread.sleep(2500); 51 | return "success"; 52 | } 53 | 54 | 55 | public String testFallback() { 56 | return "fallback"; 57 | } 58 | 59 | 60 | @HystrixCommand 61 | @GetMapping("/test1") 62 | public String test1() { 63 | if (random.nextInt(100) < 30) { 64 | int i = 1 / 0; 65 | } 66 | return "test1"; 67 | } 68 | 69 | @HystrixCommand 70 | @GetMapping("/test2") 71 | public String test2() { 72 | if (random.nextInt(100) < 20) { 73 | int i = 1 / 0; 74 | } 75 | return "test2"; 76 | } 77 | 78 | 79 | public String defaultFallback() { 80 | return "default"; 81 | } 82 | 83 | 84 | } 85 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/controller/LoadBalancerController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.controller; 2 | 3 | import com.leone.cloud.common.beans.order.OrderVO; 4 | import com.leone.cloud.common.beans.user.UserVO; 5 | import com.leone.cloud.common.entity.Order; 6 | import com.leone.cloud.common.entity.User; 7 | import com.leone.cloud.order.service.OrderService; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.cloud.client.ServiceInstance; 12 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.web.bind.annotation.GetMapping; 15 | import org.springframework.web.bind.annotation.PathVariable; 16 | import org.springframework.web.bind.annotation.RequestParam; 17 | import org.springframework.web.bind.annotation.RestController; 18 | import org.springframework.web.client.RestTemplate; 19 | 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | /** 24 | * @author Leone 25 | * @since 2018-06-20 26 | **/ 27 | @Slf4j 28 | @RestController 29 | public class LoadBalancerController { 30 | 31 | @Autowired 32 | private RestTemplate restTemplate; 33 | 34 | // @Autowired 35 | private LoadBalancerClient loadBalancerClient; 36 | 37 | @GetMapping("/user") 38 | public Object user() { 39 | return restTemplate.getForObject("http://mc-user/user", String.class); 40 | } 41 | 42 | @GetMapping("/choose") 43 | public String choose() { 44 | ServiceInstance choose = loadBalancerClient.choose("mc-user"); 45 | System.out.println(choose); 46 | return "host: " + choose.getHost() + " port: " + choose.getPort() + " serviceId: " + choose.getServiceId(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.controller; 2 | 3 | import com.leone.cloud.common.beans.order.OrderVO; 4 | import com.leone.cloud.common.beans.user.UserVO; 5 | import com.leone.cloud.common.entity.Order; 6 | import com.leone.cloud.order.service.OrderService; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.cloud.client.ServiceInstance; 11 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.web.bind.annotation.*; 14 | import org.springframework.web.client.RestTemplate; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * @author Leone 20 | * @since 2018-06-20 21 | **/ 22 | @Slf4j 23 | @RestController 24 | public class OrderController { 25 | 26 | @Autowired 27 | private OrderService orderService; 28 | 29 | @Autowired 30 | private RestTemplate restTemplate; 31 | 32 | @Autowired 33 | private LoadBalancerClient loadBalancerClient; 34 | 35 | @Value("${server.port}") 36 | private Integer port; 37 | 38 | @GetMapping(value = "/order/{orderId}") 39 | public Order findOne(@PathVariable("orderId") Long orderId) { 40 | Order order = new Order(); 41 | order.setOrderId(orderId); 42 | order.setTotalAmount(port); 43 | log.info("findOne {}", port); 44 | return order; 45 | } 46 | 47 | @GetMapping(value = "/order-list") 48 | public List list(@RequestParam(defaultValue = "1L") Long userId) { 49 | return orderService.list(userId); 50 | } 51 | 52 | @GetMapping(value = "/order/load", produces = {MediaType.APPLICATION_JSON_VALUE}) 53 | public String loadBalancer() { 54 | String url = "http://localhost:8001/info"; 55 | String result = restTemplate.getForObject("http://localhost:8001/info", String.class); 56 | 57 | ServiceInstance instance = loadBalancerClient.choose("mc-user"); 58 | log.info("instance->host:{},port:{},serviceId:{},scheme:{},url:{},metadata:{}", instance.getHost(), instance.getPort(), instance.getServiceId(), instance.getScheme(), instance.getUri(), instance.getMetadata()); 59 | UserVO user = restTemplate.getForObject(url, UserVO.class); 60 | 61 | log.info("get: -> {} result: -> {}", url, result); 62 | return result; 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/function/CircuitBreakerTest.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.function; 2 | 3 | import com.netflix.hystrix.*; 4 | 5 | /** 6 | *

断路器 7 | * 8 | * @author leone 9 | * @since 2019-03-12 10 | **/ 11 | public class CircuitBreakerTest { 12 | 13 | public static int num = 0; 14 | 15 | private static final HystrixCommand.Setter setter = HystrixCommand.Setter 16 | .withGroupKey(HystrixCommandGroupKey.Factory.asKey("circuitBreakerTestGroup")) 17 | .andCommandKey(HystrixCommandKey.Factory.asKey("circuitBreakerTestCommand")) 18 | .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("circuitBreakerTestPool")) 19 | .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() 20 | // 配置线程池 21 | .withCoreSize(10)) 22 | .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() 23 | .withCircuitBreakerEnabled(true) 24 | .withCircuitBreakerRequestVolumeThreshold(10) 25 | .withCircuitBreakerErrorThresholdPercentage(80)); 26 | 27 | // 未配置的值均取系统默认值 28 | //HystrixCommand hystrixCommand = new HystrixCommand<>(setter) { 29 | // @Override 30 | // protected Object run() throws Exception { 31 | // if (num % 2 == 0) { 32 | // return String.valueOf(num); 33 | // } else { 34 | // int j = 0; 35 | // // 死循环模拟调用超时 36 | // while (true) { 37 | // j++; 38 | // } 39 | // } 40 | // } 41 | // 42 | // @Override 43 | // protected Object getFallback() { 44 | // return "CircuitBreaker fallback: " + num; 45 | // } 46 | // 47 | //}; 48 | 49 | public static void main(String[] args) { 50 | for (int i = 0; i < 30; i++) { 51 | CircuitBreakerTest.num = i; 52 | //CircuitBreakerTest circuitBreakerTest = new CircuitBreakerTest(); 53 | //String result = (String) circuitBreakerTest.hystrixCommand.execute(); 54 | //System.out.println(result); 55 | } 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/function/SemaphoreCommandTest.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.function; 2 | 3 | import com.netflix.hystrix.HystrixCommand; 4 | import com.netflix.hystrix.HystrixCommandGroupKey; 5 | import com.netflix.hystrix.HystrixCommandProperties; 6 | 7 | import java.util.Random; 8 | 9 | /** 10 | *

资源隔离:信号量隔离 11 | * 12 | * @author leone 13 | * @since 2019-03-29 14 | **/ 15 | public class SemaphoreCommandTest extends HystrixCommand { 16 | 17 | private final int time = new Random().nextInt(1500); 18 | 19 | private final int id; 20 | 21 | public SemaphoreCommandTest(int id) { 22 | super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("SemaphoreGroup")) 23 | // 使用信号量来隔离资源只允许一定的线程执行业务代码默认 10 个 24 | .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() 25 | .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE) 26 | // 设置超时时间 27 | .withExecutionTimeoutInMilliseconds(900) 28 | // 设置信号量隔离时的最大并发请求 29 | .withExecutionIsolationSemaphoreMaxConcurrentRequests(5) 30 | // 设置fallback的最大并发数(默认 10 个) 31 | .withFallbackIsolationSemaphoreMaxConcurrentRequests(20))); 32 | this.id = id; 33 | } 34 | 35 | @Override 36 | protected String run() throws InterruptedException { 37 | // 当业务调用线程操作信号量的最大数量后就会走降级(fallback)方法 38 | Thread.sleep(time); 39 | return "id: " + id + " time: " + time; 40 | } 41 | 42 | @Override 43 | protected String getFallback() { 44 | return "id: 1 time: " + time; 45 | } 46 | 47 | static class UnitTest { 48 | public static void main(String[] args) { 49 | for (int i = 0; i < 25; i++) { 50 | SemaphoreCommandTest command = new SemaphoreCommandTest(2000); 51 | new Thread(() -> { 52 | String execute = null; 53 | try { 54 | execute = command.queue().get(); 55 | // execute = command.execute(); 56 | } catch (Exception e) { 57 | e.printStackTrace(); 58 | } 59 | if (execute.startsWith("id: 1")) { 60 | System.err.println(Thread.currentThread().getName() + "\t\t" + execute); 61 | } else { 62 | System.out.println(Thread.currentThread().getName() + "\t\t" + execute); 63 | } 64 | }).start(); 65 | } 66 | } 67 | } 68 | 69 | } 70 | 71 | 72 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/function/ThreadPoolCommandTest.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.function; 2 | 3 | import com.netflix.hystrix.*; 4 | 5 | import java.util.Random; 6 | import java.util.concurrent.Future; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | * hystrix 资源隔离:线程池隔离 11 | * 12 | * @author leone 13 | * @since 2019-03-12 14 | **/ 15 | public class ThreadPoolCommandTest extends HystrixCommand { 16 | 17 | private final String name; 18 | 19 | private final int time = new Random().nextInt(999); 20 | 21 | /** 22 | * 在继承hystrixCommand的构造函数中实现添加线程池参数记性资源隔离 23 | * 24 | * @param name name 25 | */ 26 | public ThreadPoolCommandTest(String name) { 27 | super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) 28 | .andCommandKey(HystrixCommandKey.Factory.asKey("ExampleCommand")) 29 | .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("ExampleThreadPool")) 30 | .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter() 31 | // hystrix核心线程数默认10个 32 | .withCoreSize(5) 33 | // 最大排队长度。默认-1 34 | .withMaxQueueSize(10) 35 | // 排队线程数量阈值,默认为5,达到时拒绝,如果配置了该选项,队列的大小是该队列 如果maxQueueSize=-1的话,则该选项不起作用 36 | .withQueueSizeRejectionThreshold(7)) 37 | .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() 38 | // 打开timeout开关 39 | .withExecutionTimeoutEnabled(true) 40 | // 设置超时时间 41 | .withExecutionTimeoutInMilliseconds(1000) 42 | ) 43 | ); 44 | this.name = name; 45 | } 46 | 47 | /** 48 | * 依赖逻辑封装在run()方法中 49 | * 50 | * @return string 51 | */ 52 | @Override 53 | protected String run() throws InterruptedException { 54 | Thread.sleep(time); 55 | return "run:" + name + "\t\t" + time + "\t\t" + Thread.currentThread().getName(); 56 | } 57 | 58 | /** 59 | * 失败调用降级方法 60 | * 61 | * @return str 62 | */ 63 | @Override 64 | protected String getFallback() { 65 | return "fallback \t\t time: " + time + "\t\t" + Thread.currentThread().getName(); 66 | } 67 | 68 | 69 | public static void main(String[] args) throws Exception { 70 | // 模拟使用2个线程调用业务代码 71 | for (int i = 0; i < 20; i++) { 72 | // 每个Command对象不可以重复调用,否则报错:This instance can only be executed once. Please instantiate a new instance. 73 | ThreadPoolCommandTest command = new ThreadPoolCommandTest("james"); 74 | new Thread(() -> { 75 | String execute = ""; 76 | try { 77 | // 异步调用,可自由控制获取结果时机 78 | Future queue = command.queue(); 79 | // get操作不能超过command定义的超时时间,默认:1秒 80 | execute = queue.get(100, TimeUnit.MINUTES); 81 | 82 | // 使用execute() 同步调用代码,效果等同于:helloWorldCommandTest.queue().get(); 83 | // execute = command.execute(); 84 | // execute = command.queue().get(); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } 88 | if (execute.startsWith("fallback")) { 89 | System.err.println(execute); 90 | } else { 91 | System.out.println(execute); 92 | } 93 | }).start(); 94 | } 95 | 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/function/TimeOutCommandTest.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.function; 2 | 3 | import com.netflix.hystrix.HystrixCommand; 4 | import com.netflix.hystrix.HystrixCommandGroupKey; 5 | import com.netflix.hystrix.HystrixCommandProperties; 6 | 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | *

重载HystrixCommand 的getFallback方法实现逻辑 11 | * 12 | * @author leone 13 | * @since 2019-03-13 14 | **/ 15 | public class TimeOutCommandTest extends HystrixCommand { 16 | 17 | private final String name; 18 | 19 | public TimeOutCommandTest(String name) { 20 | super(Setter.withGroupKey( 21 | HystrixCommandGroupKey.Factory.asKey("HelloWorldGroup")) 22 | // 配置依赖超时时间,500毫秒 23 | .andCommandPropertiesDefaults(HystrixCommandProperties.Setter(). 24 | withExecutionIsolationThreadTimeoutInMilliseconds(500))); 25 | this.name = name; 26 | } 27 | 28 | @Override 29 | protected String getFallback() { 30 | return "executor failed fallback"; 31 | } 32 | 33 | @Override 34 | protected String run() throws Exception { 35 | // sleep 600毫秒,调用会超时 36 | TimeUnit.MILLISECONDS.sleep(600); 37 | return "name: " + name + " thread name: " + Thread.currentThread().getName(); 38 | } 39 | 40 | public static void main(String[] args) throws Exception { 41 | TimeOutCommandTest command = new TimeOutCommandTest("test-Fallback"); 42 | String result = command.execute(); 43 | System.out.println(result); 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/service/FeignOrderService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.service; 2 | 3 | import com.leone.cloud.common.beans.order.OrderVO; 4 | import com.leone.cloud.common.beans.user.UserVO; 5 | import com.leone.cloud.common.entity.Order; 6 | import com.leone.cloud.common.utils.EntityFactory; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.BeanUtils; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.util.ObjectUtils; 13 | import org.springframework.web.client.RestTemplate; 14 | 15 | import java.util.List; 16 | import java.util.stream.Collectors; 17 | 18 | /** 19 | *

20 | * 21 | * @author leone 22 | * @since 2019-01-22 23 | **/ 24 | @Slf4j 25 | // @Service 26 | public class FeignOrderService { 27 | 28 | private String userUrl = "http://localhost:9001/user/"; 29 | 30 | @Autowired 31 | private RestTemplate restTemplate; 32 | 33 | @Autowired 34 | private LoadBalancerClient loadBalancerClient; 35 | 36 | /** 37 | * @param orderId 38 | * @return 39 | */ 40 | public OrderVO findOne(Long orderId) { 41 | Order order = EntityFactory.getOrder(orderId); 42 | String url = userUrl + order.getUserId(); 43 | UserVO user = restTemplate.getForObject(url, UserVO.class); 44 | log.info("get: -> {} result: -> {}", url, user); 45 | if (ObjectUtils.isEmpty(user)) { 46 | return null; 47 | } 48 | OrderVO vo = new OrderVO(); 49 | BeanUtils.copyProperties(order, vo); 50 | vo.setUserAccount(user.getAccount()); 51 | vo.setUserAge(user.getAge()); 52 | vo.setUserDescription(user.getDescription()); 53 | return vo; 54 | } 55 | 56 | /** 57 | * @param userId 58 | * @return 59 | */ 60 | public List list(Long userId) { 61 | String url = userUrl + userId; 62 | /*ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() { 63 | }; 64 | 65 | List users = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>() { 66 | }).getBody();*/ 67 | 68 | UserVO user = restTemplate.getForObject(url, UserVO.class); 69 | log.info("get: -> {} result: -> {}", url, user); 70 | if (ObjectUtils.isEmpty(user)) { 71 | return null; 72 | } 73 | List orders = EntityFactory.getOrderList(userId); 74 | return orders.stream().map(e -> { 75 | OrderVO vo = new OrderVO(); 76 | BeanUtils.copyProperties(e, vo); 77 | vo.setUserAccount(user.getAccount()); 78 | vo.setUserAge(user.getAge()); 79 | vo.setUserDescription(user.getDescription()); 80 | return vo; 81 | }).collect(Collectors.toList()); 82 | } 83 | 84 | 85 | } 86 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.service; 2 | 3 | import com.leone.cloud.common.entity.Order; 4 | import com.leone.cloud.common.utils.EntityFactory; 5 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.*; 10 | 11 | /** 12 | *

13 | * 14 | * @author leone 15 | * @since 2019-01-22 16 | **/ 17 | @Slf4j 18 | @Service 19 | public class OrderService { 20 | 21 | /** 22 | * @param orderId orderId 23 | * @return order 24 | */ 25 | @HystrixCommand(fallbackMethod = "findOneFallback") 26 | public Order findOne(Long orderId) { 27 | Order order = EntityFactory.getOrder(orderId); 28 | if (new Random().nextBoolean()) { 29 | throw new RuntimeException("自定义异常 orderService.findOne"); 30 | } 31 | return order; 32 | } 33 | 34 | public Order findOneFallback(Long orderId) { 35 | //log.error("findOneFallback orderId: {}", orderId); 36 | return EntityFactory.getDefaultOrder(); 37 | } 38 | 39 | /** 40 | * @param userId userId 41 | * @return list 42 | */ 43 | public List list(Long userId) { 44 | /*ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() { 45 | }; 46 | List users = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>() { 47 | }).getBody();*/ 48 | return EntityFactory.getOrderList(userId); 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/java/com/leone/cloud/order/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.order.service; 2 | 3 | import com.leone.cloud.common.entity.User; 4 | import org.springframework.web.bind.annotation.RequestParam; 5 | import org.springframework.web.service.annotation.GetExchange; 6 | 7 | import java.util.List; 8 | 9 | public interface UserService { 10 | 11 | @GetExchange("/user-def") 12 | User findOne(@RequestParam("userId")Long userId); 13 | 14 | List list(); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /spring-cloud-order/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9002 3 | 4 | spring: 5 | application: 6 | name: mc-order 7 | 8 | eureka: 9 | client: 10 | serviceUrl: 11 | defaultZone: http://localhost:8761/eureka 12 | 13 | 14 | 15 | # 新版本中需要独立设置开启feign对hystrix的支持,旧版本中默认开启对hystrix支持 16 | #feign: 17 | # hystrix: 18 | # enabled: true 19 | 20 | 21 | # 配置hystrix 22 | #hystrix: 23 | # threadpool: 24 | # default: 25 | # # hystrix核心线程池线程数 26 | # coreSize: 10 27 | # metrics: 28 | # polling-interval-ms: 2000 29 | # enabled: true 30 | # command: 31 | # # IService#hello(): 设置某一个接口 default: 设置全部接口 32 | # default: 33 | # execution: 34 | # timeout: 35 | # # 开启超时熔断功能 36 | # enabled: true 37 | # isolation: 38 | # thread: 39 | # timeoutInMilliseconds: 2000 # 超时时间 40 | # circuitBreaker: 41 | # requestVolumeThreshold: 3 # 当在配置时间窗口内达到此数量后,进行短路。默认20个 42 | # sleepWindowInMilliseconds: 5 # 短路多久以后开始尝试是否恢复,默认5s 43 | # errorThresholdPercentage: 50% # 出错百分比阈值,当达到此阈值后,开始短路。默认50% 44 | 45 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | spring-cloud-ribbon-hystrix 7 | jar 8 | 9 | 10 | com.leone.cloud 11 | spring-cloud-examples 12 | 2.0.0.RELEASE 13 | 14 | 15 | 16 | 17 | UTF-8 18 | 19 | 20 | 21 | 22 | 23 | org.springframework.cloud 24 | spring-cloud-dependencies 25 | 2023.0.3 26 | pom 27 | import 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-dependencies 32 | 3.3.5 33 | pom 34 | import 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-devtools 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-netflix-eureka-client 47 | 48 | 49 | org.springframework.cloud 50 | spring-cloud-starter-netflix-ribbon 51 | 2.2.9.RELEASE 52 | 53 | 54 | org.springframework.cloud 55 | spring-cloud-starter-netflix-hystrix 56 | 2.2.10.RELEASE 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter-actuator 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-web 65 | 66 | 67 | 68 | com.leone.cloud 69 | spring-cloud-common 70 | 2.0.0.RELEASE 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-compiler-plugin 80 | 3.8.0 81 | 82 | 17 83 | 17 84 | UTF-8 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/src/main/java/com/leone/RibbonHystrixApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 5 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 6 | import org.springframework.cloud.netflix.ribbon.RibbonClient; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.web.client.RestTemplate; 9 | 10 | /** 11 | * @author Leone 12 | * @since 2017-11-22 13 | **/ 14 | @RibbonClient(value = "spring-cloud-provider") 15 | @EnableDiscoveryClient 16 | public class RibbonHystrixApplication { 17 | 18 | public static void main(String[] args) { 19 | SpringApplication.run(RibbonHystrixApplication.class, args); 20 | } 21 | 22 | @Bean 23 | @LoadBalanced 24 | public RestTemplate restTemplate(){ 25 | return new RestTemplate(); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/src/main/java/com/leone/cloud/ribbon/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.ribbon.controller; 2 | 3 | import com.leone.cloud.ribbon.entity.User; 4 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import org.springframework.web.client.RestTemplate; 11 | 12 | import java.util.Date; 13 | 14 | /** 15 | * @author Leone 16 | * @since 2017-12-22 17 | **/ 18 | @Slf4j 19 | @RestController 20 | public class OrderController { 21 | 22 | @Autowired 23 | private RestTemplate restTemplate; 24 | 25 | @GetMapping("/user/{id}") 26 | @HystrixCommand(fallbackMethod = "findByIdFallback"/*, commandProperties=@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")*/) 27 | public User user(@PathVariable("id") int id) { 28 | log.info("订单服务获取用户信息->http://spring-cloud-provider/user/{}", id); 29 | return restTemplate.getForObject("http://spring-cloud-provider/user/" + id, User.class); 30 | } 31 | 32 | //fallback 方法的返回值和参数要和原始方法一致 33 | public User findByIdFallback(int id) { 34 | log.info("订单服务获取用户信息的fallback方法->param:id={}", id); 35 | return new User(12, new Date(), "james", "password", "15687793324"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/src/main/java/com/leone/cloud/ribbon/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.ribbon.entity; 2 | 3 | //import io.swagger.annotations.ApiModel; 4 | import lombok.Data; 5 | 6 | import java.util.Date; 7 | 8 | @Data 9 | //@ApiModel 10 | public class User { 11 | 12 | private Integer userId; 13 | 14 | private Date birthday; 15 | 16 | private String username; 17 | 18 | private String password; 19 | 20 | private String phone; 21 | 22 | public User() { 23 | } 24 | 25 | public User(Integer userId, Date birthday, String username, String password, String phone) { 26 | this.userId = userId; 27 | this.birthday = birthday; 28 | this.username = username; 29 | this.password = password; 30 | this.phone = phone; 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: spring-cloud-provider-ribbon-hystrix 4 | 5 | server: 6 | port: 8108 7 | 8 | eureka: 9 | client: 10 | healthcheck: 11 | enabled: true 12 | serviceUrl: 13 | defaultZone: http://localhost:8761/eureka 14 | 15 | hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000 16 | -------------------------------------------------------------------------------- /spring-cloud-ribbon-hystrix/src/main/resources/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janlle/spring-cloud-examples/8f0e0dbb7b9c95dda7920c569657640d25387c18/spring-cloud-ribbon-hystrix/src/main/resources/config.properties -------------------------------------------------------------------------------- /spring-cloud-sidecar/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | spring-cloud-sidecar 6 | jar 7 | 8 | 9 | com.leone.cloud 10 | spring-cloud-examples 11 | 2.0.0.RELEASE 12 | 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | org.springframework.cloud 40 | spring-cloud-starter-netflix-zuul 41 | 2.0.2.RELEASE 42 | 43 | 44 | org.springframework.cloud 45 | spring-cloud-starter-netflix-eureka-client 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-netflix-sidecar 50 | 2.0.1.RELEASE 51 | 52 | 53 | 54 | 55 | 56 | 57 | org.apache.maven.plugins 58 | maven-compiler-plugin 59 | 3.8.0 60 | 61 | 17 62 | 17 63 | UTF-8 64 | 65 | 66 | 67 | 68 | org.springframework.boot 69 | spring-boot-maven-plugin 70 | 2.0.3.RELEASE 71 | 72 | 73 | ZIP 74 | 75 | 76 | 77 | 78 | repackage 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /spring-cloud-sidecar/src/main/java/com/leone/cloud/sidecar/SidecarApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.sidecar; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.sidecar.EnableSidecar; 6 | 7 | @EnableSidecar 8 | @SpringBootApplication 9 | public class SidecarApplication { 10 | public static void main(String[] args) { 11 | SpringApplication.run(SidecarApplication.class, args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /spring-cloud-sidecar/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: springCloud-sidecar 4 | 5 | server: 6 | port: 8120 7 | 8 | eureka: 9 | client: 10 | service-url: 11 | defaultZone: http://user:password123@localhost:8761/eureka 12 | instance: 13 | prefer-ip-address: true 14 | 15 | #通过设置这个属性可以访问这个url http://localhost:8111/routes 16 | management: 17 | security: 18 | enabled: false 19 | 20 | sidecar: 21 | port: 8001 22 | health-uri: http://localhost:8001/health.json 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spring-cloud-sleuth/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-sleuth 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | io.spring.platform 22 | platform-bom 23 | Cairo-SR2 24 | pom 25 | import 26 | 27 | 28 | org.springframework.cloud 29 | spring-cloud-dependencies 30 | Finchley.SR2 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-starter-sleuth 44 | 45 | 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-starter-zipkin 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-compiler-plugin 69 | 3.8.0 70 | 71 | 17 72 | 17 73 | UTF-8 74 | 75 | 76 | 77 | 78 | org.springframework.boot 79 | spring-boot-maven-plugin 80 | 2.0.3.RELEASE 81 | 82 | 83 | ZIP 84 | 85 | 86 | 87 | 88 | repackage 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /spring-cloud-sleuth/src/main/java/com/leone/cloud/sleuth/SleuthApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.sleuth; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | *

8 | * 9 | * @author Leone 10 | * @since 2018-10-26 11 | **/ 12 | @SpringBootApplication 13 | public class SleuthApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(SleuthApplication.class, args); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /spring-cloud-sleuth/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | # 本服务注册到注册到服务器的名称, 这个名称就是后面调用服务时的服务标识符 4 | name: cloud-dashboard-zipkin 5 | zipkin: 6 | enabled: true 7 | # zipkkin dashboard的地址:通过真实IP地址访问 8 | baseUrl: http://localhost:17601/ 9 | # 通过cloud-dashboard-zipkin注册到注册中心的服务名称访问,本版本(spring-cloud-sleuth-core-1.2.5.RELEASE)不支持,需要从spring-cloud-sleuth-core-1.3.0.RELEASE开始支持这个功能 10 | # 配置如下: 11 | # baseUrl: http://cloud-dashboard-zipkin/ 12 | sleuth: 13 | sampler: 14 | # 默认值为0.1f,现在为了测试设置100%采集 15 | percentage: 1 16 | 17 | eureka: 18 | client: 19 | serviceUrl: 20 | # 服务器注册/获取服务器的zone 21 | defaultZone: http://127.0.0.1:10761/eureka/ 22 | # defaultZone: http://192.168.21.3:10761/eureka/,http://192.168.21.4:10761/eureka/ 23 | instance: 24 | prefer-ip-address: true 25 | -------------------------------------------------------------------------------- /spring-cloud-stream/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | spring-cloud-examples 7 | com.leone.cloud 8 | 2.0.0.RELEASE 9 | 10 | 4.0.0 11 | 12 | spring-cloud-stream 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-web 41 | 42 | 43 | 44 | org.springframework.cloud 45 | spring-cloud-starter-netflix-eureka-client 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-actuator 51 | 52 | 53 | 54 | org.springframework.cloud 55 | spring-cloud-stream-binder-rabbit 56 | 2.0.2.RELEASE 57 | 58 | 59 | 60 | org.springframework.cloud 61 | spring-cloud-starter-netflix-hystrix 62 | 2.2.10.RELEASE 63 | 64 | 65 | 66 | com.leone.cloud 67 | spring-cloud-common 68 | 2.0.0.RELEASE 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-compiler-plugin 78 | 3.8.0 79 | 80 | 17 81 | 17 82 | UTF-8 83 | 84 | 85 | 86 | 87 | org.springframework.boot 88 | spring-boot-maven-plugin 89 | 2.0.3.RELEASE 90 | 91 | 92 | ZIP 93 | 94 | 95 | 96 | 97 | repackage 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/StreamApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 5 | 6 | /** 7 | * @author Leone 8 | * @since 2018-06-23 9 | **/ 10 | @EnableDiscoveryClient 11 | public class StreamApplication { 12 | public static void main(String[] args) { 13 | SpringApplication.run(StreamApplication.class, args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/controller/MessageController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream.controller; 2 | 3 | import com.leone.cloud.stream.message.Source; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.messaging.support.MessageBuilder; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import java.util.Date; 11 | 12 | /** 13 | * @author Leone 14 | * @since 2018-06-23 15 | **/ 16 | @Slf4j 17 | @RestController 18 | public class MessageController { 19 | 20 | @Autowired 21 | private Source source; 22 | 23 | @GetMapping("/send") 24 | public void process() { 25 | String message = "now" + new Date(); 26 | source.output1().send(MessageBuilder.withPayload(message).build()); 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/message/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream.message; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | //import org.springframework.cloud.stream.annotation.EnableBinding; 5 | //import org.springframework.cloud.stream.annotation.StreamListener; 6 | 7 | /** 8 | * 用来指定一个或多个定义了@Input 或者 @Output注解的接口,实现对消息通道的绑定。Sink接口是默认输入消息通道绑定接口 9 | * 10 | * @author Leone 11 | * @since 2018-06-23 12 | **/ 13 | @Slf4j 14 | //@EnableBinding({Sink.class, Source.class}) 15 | public class Consumer { 16 | 17 | //@StreamListener(Sink.INPUT1) 18 | public void receive1(Object object) { 19 | log.info("message:{}", object); 20 | } 21 | 22 | //@StreamListener(Sink.INPUT2) 23 | public void receive2(Object object) { 24 | log.info("message:{}", object); 25 | } 26 | 27 | 28 | } 29 | -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/message/Processor.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream.message; 2 | 3 | /** 4 | * 包含input、output 5 | * 6 | * @author Leone 7 | * @since 2018-02-24 8 | **/ 9 | public interface Processor extends Source, Sink { 10 | 11 | 12 | } -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/message/Sink.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream.message; 2 | 3 | import org.springframework.messaging.SubscribableChannel; 4 | 5 | 6 | /** 7 | *

input 通道接口 8 | * 9 | * @author leone 10 | * @since 2019-01-28 11 | **/ 12 | public interface Sink { 13 | 14 | String INPUT1 = "input1"; 15 | String INPUT2 = "input2"; 16 | 17 | 18 | //@Input(Sink.INPUT1) 19 | SubscribableChannel input1(); 20 | 21 | //@Input(Sink.INPUT2) 22 | SubscribableChannel input2(); 23 | 24 | 25 | } -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/java/com/leone/cloud/stream/message/Source.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.stream.message; 2 | 3 | import org.springframework.messaging.MessageChannel; 4 | import org.springframework.messaging.SubscribableChannel; 5 | import org.springframework.stereotype.Component; 6 | 7 | /** 8 | *

output通道接口 9 | * 10 | * @author leone 11 | * @since 2019-01-28 12 | **/ 13 | @Component 14 | public interface Source { 15 | 16 | String OUTPUT1 = "output1"; 17 | 18 | String OUTPUT2 = "output2"; 19 | 20 | //@Input("aa") 21 | SubscribableChannel input(); 22 | 23 | //@Output(Source.OUTPUT1) 24 | MessageChannel output1(); 25 | 26 | //@Output(Source.OUTPUT2) 27 | MessageChannel output2(); 28 | 29 | } -------------------------------------------------------------------------------- /spring-cloud-stream/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | servlet: 4 | path: / 5 | 6 | spring: 7 | application: 8 | name: spring-cloud-stream 9 | rabbitmq: 10 | host: localhost 11 | port: 5672 12 | username: cloud 13 | password: xxxx 14 | virtual-host: /cloud 15 | cloud: 16 | stream: 17 | bindings: 18 | input1: 19 | destination: wdtest1 20 | content-type: application/json 21 | group: g1 22 | input2: 23 | destination: wdtest2 24 | content-type: application/json 25 | group: g1 26 | input3: 27 | destination: wdtest3 28 | content-type: application/json 29 | group: g1 30 | input4: 31 | destination: wdtest4 32 | content-type: application/json 33 | group: g1 34 | 35 | 36 | eureka: 37 | client: 38 | service-url: 39 | defaultZone: http://localhost:8761/eureka 40 | 41 | management: 42 | endpoints: 43 | web: 44 | exposure: 45 | include: "*" -------------------------------------------------------------------------------- /spring-cloud-turbine/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | spring-cloud-turbine 5 | 6 | 7 | com.leone.cloud 8 | spring-cloud-examples 9 | 2.0.0.RELEASE 10 | 11 | 12 | 13 | UTF-8 14 | 15 | 16 | 17 | 18 | 19 | io.spring.platform 20 | platform-bom 21 | Cairo-SR6 22 | pom 23 | import 24 | 25 | 26 | org.springframework.cloud 27 | spring-cloud-dependencies 28 | Finchley.RELEASE 29 | pom 30 | import 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.springframework.cloud 38 | spring-cloud-starter-config 39 | 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-starter-netflix-eureka-server 44 | 45 | 46 | 47 | org.springframework.cloud 48 | spring-cloud-netflix-turbine 49 | 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-actuator 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.apache.maven.plugins 62 | maven-compiler-plugin 63 | 3.7.0 64 | 65 | 17 66 | 17 67 | UTF-8 68 | 69 | 70 | 71 | 72 | org.springframework.boot 73 | spring-boot-maven-plugin 74 | 2.0.3.RELEASE 75 | 76 | 77 | ZIP 78 | 79 | 80 | 81 | 82 | repackage 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /spring-cloud-turbine/src/main/java/com/leone/cloud/turbine/TurbineApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.turbine; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.turbine.EnableTurbine; 6 | 7 | /** 8 | *

9 | * 10 | * @author Leone 11 | * @since 2018-05-13 12 | **/ 13 | @EnableTurbine 14 | @SpringBootApplication 15 | public class TurbineApplication { 16 | public static void main(String[] args) { 17 | SpringApplication.run(TurbineApplication.class, args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-cloud-turbine/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: mc-turbine 4 | server: 5 | port: 9999 6 | 7 | eureka: 8 | client: 9 | serviceUrl: 10 | defaultZone: http://localhost:8761/eureka 11 | instance: 12 | appname: turbine-service 13 | instance-id: ${spring.application.name}:${server.port} 14 | ip-address: 127.0.0.1 15 | turbine: 16 | aggregator: 17 | cluster-config: default 18 | app-config: user-service,orderItem-service,order-service 19 | cluster-name-expression: new String("default") 20 | 21 | management: 22 | endpoints: 23 | web: 24 | exposure: 25 | include: "*" 26 | base-path: /actuator 27 | endpoint: 28 | health: 29 | show-details: always -------------------------------------------------------------------------------- /spring-cloud-turbine/src/main/resources/config.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janlle/spring-cloud-examples/8f0e0dbb7b9c95dda7920c569657640d25387c18/spring-cloud-turbine/src/main/resources/config.properties -------------------------------------------------------------------------------- /spring-cloud-user/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | spring-cloud-user 6 | 7 | 8 | com.leone.cloud 9 | spring-cloud-examples 10 | 2.0.0.RELEASE 11 | 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | 20 | org.springframework.cloud 21 | spring-cloud-dependencies 22 | 2023.0.3 23 | pom 24 | import 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-dependencies 29 | 3.3.5 30 | pom 31 | import 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-web 40 | 41 | 42 | 43 | org.springframework.cloud 44 | spring-cloud-starter-netflix-eureka-client 45 | 46 | 47 | 48 | org.springframework.cloud 49 | spring-cloud-starter-netflix-ribbon 50 | 2.2.10.RELEASE 51 | 52 | 53 | 54 | org.springframework.cloud 55 | spring-cloud-starter-openfeign 56 | 4.1.3 57 | 58 | 59 | 60 | com.leone.cloud 61 | spring-cloud-common 62 | 2.0.0.RELEASE 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | org.apache.maven.plugins 93 | maven-compiler-plugin 94 | 3.8.0 95 | 96 | 17 97 | 17 98 | UTF-8 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/UserApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.ribbon.RibbonClient; 7 | import org.springframework.cloud.netflix.ribbon.RibbonClients; 8 | import org.springframework.cloud.openfeign.EnableFeignClients; 9 | 10 | 11 | /** 12 | *

生产者 服务提供者 上游服务 13 | * 14 | * @author Leone 15 | * @since 2018-03-10 16 | **/ 17 | @EnableFeignClients 18 | @EnableDiscoveryClient 19 | @SpringBootApplication 20 | @RibbonClients({@RibbonClient(name = "mc-order")}) 21 | public class UserApplication { 22 | public static void main(String[] args) { 23 | SpringApplication.run(UserApplication.class, args); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/config/FeignConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.config; 2 | 3 | // import feign.Contract; 4 | // import feign.Logger; 5 | // import feign.auth.BasicAuthRequestInterceptor; 6 | import feign.Contract; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | 10 | /** 11 | * @author Leone 12 | * @since 2017-11-13 13 | **/ 14 | @Configuration 15 | public class FeignConfig { 16 | 17 | // @Bean 18 | // public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { 19 | // return new BasicAuthRequestInterceptor("user", "password123"); 20 | // } 21 | 22 | // @Bean 23 | // public Logger.Level feignLoggerLevel() { 24 | // return Logger.Level.FULL; 25 | // } 26 | 27 | @Bean 28 | public Contract feignContract() { 29 | return new Contract.Default(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/config/RibbonConfig.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.config; 2 | 3 | import com.netflix.loadbalancer.AvailabilityFilteringRule; 4 | import com.netflix.loadbalancer.IRule; 5 | import com.netflix.loadbalancer.RandomRule; 6 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.web.client.RestTemplate; 10 | 11 | /** 12 | *

13 | * 14 | * @author leone 15 | * @since 2019-04-04 16 | **/ 17 | @Configuration 18 | public class RibbonConfig { 19 | 20 | /* 21 | * 实例化ribbon使用的RestTemplate 22 | */ 23 | @Bean 24 | @LoadBalanced 25 | public RestTemplate restTemplate() { 26 | return new RestTemplate(); 27 | } 28 | 29 | /** 30 | * 配置随机负载策略,需要配置属性 mc-order.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule 31 | */ 32 | @Bean 33 | public IRule ribbonRule() { 34 | // 轮询 35 | // return new RoundRobinRule(); 36 | 37 | // 权重 根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。 38 | // return new WeightedResponseTimeRule(); 39 | 40 | // 重试 先按照轮询策略获取服务,如果获取失败则在指定时间内重试,获取可用服务 41 | // return new RetryRule(); 42 | 43 | // 选择一个最小的并发请求的server 44 | // return new BestAvailableRule(); 45 | 46 | // 符合判断server所在区域的性能和server的可用性选择服务 47 | // return new ZoneAvoidanceRule(); 48 | 49 | // 随机 50 | return new RandomRule(); 51 | 52 | // 过滤掉那些因为一直连接失败的被标记为circuit tripped的后端server,并过滤掉那些高并发的的后端server(active connections 超过配置的阈值) 53 | // return new AvailabilityFilteringRule(); 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/controller/FeignController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.controller; 2 | 3 | import com.leone.cloud.common.beans.user.UserAddVO; 4 | import com.leone.cloud.common.beans.user.UserEditVO; 5 | import com.leone.cloud.common.beans.user.UserVO; 6 | import com.leone.cloud.common.entity.Order; 7 | import com.leone.cloud.common.entity.User; 8 | import com.leone.cloud.user.feign.OrderFeignService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.web.bind.annotation.*; 13 | 14 | import java.util.HashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | import java.util.stream.Collectors; 18 | 19 | /** 20 | * @author Leone 21 | * @since 2017-10-22 22 | **/ 23 | @RestController 24 | @RequestMapping("/feign") 25 | public class FeignController { 26 | 27 | @Autowired 28 | private OrderFeignService orderFeignService; 29 | 30 | @GetMapping(value = "/user") 31 | public List list(@RequestParam(defaultValue = "1L") Long userId) { 32 | // Map.of("userId", userId) 33 | List orders = orderFeignService.list(); 34 | return orders.stream().map(e -> { 35 | User user = new User(); 36 | user.setUserId(e.getUserId()); 37 | user.setAccount(e.getTotalAmount().toString()); 38 | return user; 39 | }).collect(Collectors.toList()); 40 | } 41 | 42 | @GetMapping("/user/{id}") 43 | public Order user(@PathVariable("id") Long id) { 44 | Map headers = new HashMap<>(); 45 | headers.put("a", "aa"); 46 | headers.put("b", "bb"); 47 | return orderFeignService.find(id, headers); 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/controller/RibbonController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.controller; 2 | 3 | import com.leone.cloud.common.entity.Order; 4 | import com.leone.cloud.common.entity.User; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.cloud.client.ServiceInstance; 8 | import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; 9 | import org.springframework.web.bind.annotation.*; 10 | import org.springframework.web.client.RestTemplate; 11 | 12 | import java.util.Map; 13 | 14 | /** 15 | * @author Leone 16 | * @since 2018-12-21 17 | **/ 18 | @RestController 19 | @RequestMapping("/ribbon") 20 | public class RibbonController { 21 | 22 | @Autowired 23 | private RestTemplate restTemplate; 24 | 25 | @Autowired 26 | private LoadBalancerClient loadBalancerClient; 27 | 28 | @GetMapping("/{userId}") 29 | public Map order(@PathVariable("userId") int userId) { 30 | Order order = restTemplate.getForObject("http://mc-order/order/" + userId, Order.class); 31 | return Map.of("user_id", userId, "order_count", order == null ? 0 : order.getTotalAmount()); 32 | } 33 | 34 | @GetMapping("/choose") 35 | public String choose() { 36 | ServiceInstance choose = loadBalancerClient.choose("mc-order"); 37 | System.out.println(choose); 38 | return "host: " + choose.getHost() + " port: " + choose.getPort() + " serviceId: " + choose.getServiceId(); 39 | } 40 | 41 | @GetMapping("/withouteureka") 42 | public Map withOutEureka(@RequestParam int userId) { 43 | ServiceInstance choose = loadBalancerClient.choose("mc-order"); 44 | Order order = restTemplate.getForObject(String.format("http://%s:%s/user/%d", choose.getHost(), choose.getPort(), userId), Order.class); 45 | return Map.of("user_id", userId, "order_count", order == null ? 0 : order.getTotalAmount()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.controller; 2 | 3 | import com.leone.cloud.common.entity.User; 4 | import com.leone.cloud.user.service.UserService; 5 | import com.netflix.appinfo.InstanceInfo; 6 | import com.netflix.discovery.EurekaClient; 7 | import lombok.extern.slf4j.Slf4j; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.cloud.client.discovery.DiscoveryClient; 11 | import org.springframework.http.HttpHeaders; 12 | import org.springframework.web.bind.annotation.*; 13 | import org.springframework.web.multipart.MultipartFile; 14 | 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.io.OutputStream; 19 | 20 | 21 | /** 22 | *

23 | * 24 | * @author Leone 25 | * @since 2018-03-10 26 | **/ 27 | @Slf4j 28 | @RestController 29 | public class UserController { 30 | 31 | @Autowired 32 | private EurekaClient eurekaClient; 33 | 34 | @Autowired 35 | private DiscoveryClient discoveryClient; 36 | 37 | @Autowired 38 | private UserService userService; 39 | 40 | @Value("${server.port}") 41 | private Integer port; 42 | 43 | @GetMapping("/user") 44 | public Object user(@RequestHeader HttpHeaders headers) { 45 | log.info("mc-user service port: {} info: {}", port, discoveryClient.getServices()); 46 | log.info("header InstanceId: {}", headers.get("X-InstanceId")); 47 | //log.info("request header:{}", headers.get("User-Agent")); 48 | //headers.getAccessControlAllowHeaders().forEach(System.out::println); 49 | InstanceInfo instance = eurekaClient.getNextServerFromEureka("mc-user", false); 50 | log.info("instance: {}", instance); 51 | User user = userService.findOne(1L); 52 | user.setAge(port); 53 | return user; 54 | } 55 | 56 | // @RequestParam(defaultValue = "1", required = false, name = "userId") Long userId 57 | @GetMapping("/user/list") 58 | public Object userList() { 59 | return userService.list(); 60 | } 61 | 62 | /** 63 | * 上传文件 64 | * 有界面的测试:... 65 | * 使用命令:curl -F "file=@文件全名" localhost:9001/user/upload 66 | * 67 | * @param file 待上传的文件 68 | * @return 文件在服务器上的绝对路径 69 | * @throws IOException IO异常 70 | */ 71 | @PostMapping("/user/upload") 72 | public String upload(MultipartFile file) throws IOException { 73 | if (null != file) { 74 | String fileName = file.getOriginalFilename(); 75 | log.info("fileName:{} port: {}", fileName, port); 76 | InputStream inputStream = file.getInputStream(); 77 | OutputStream outputStream = new FileOutputStream("E:/tmp/upload/" + fileName); 78 | int len; 79 | byte[] bytes = new byte[1024]; 80 | while ((len = inputStream.read(bytes)) != -1) { 81 | outputStream.write(bytes, 0, len); 82 | } 83 | outputStream.close(); 84 | inputStream.close(); 85 | return fileName; 86 | } 87 | return "error"; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/controller/ZkController.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.controller; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.cloud.client.ServiceInstance; 6 | import org.springframework.cloud.client.discovery.DiscoveryClient; 7 | import org.springframework.cloud.context.config.annotation.RefreshScope; 8 | import org.springframework.core.env.Environment; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | *

16 | * 17 | * @author Leone 18 | * @since 2018-10-26 19 | **/ 20 | @RefreshScope 21 | @RestController 22 | public class ZkController { 23 | 24 | @Autowired 25 | private DiscoveryClient discoveryClient; 26 | 27 | @Value("${spring.application.name}") 28 | private String instanceName; 29 | 30 | @Autowired 31 | private Environment environment; 32 | 33 | @GetMapping("/instance") 34 | public String instance() { 35 | //获取实例化的注册节点 36 | List list = discoveryClient.getInstances(instanceName); 37 | 38 | //获取实例化的服务 39 | StringBuffer sb = new StringBuffer(); 40 | if (list != null && list.size() > 0) { 41 | sb.append(list.get(0).getUri()); 42 | } 43 | 44 | return "hello world " + sb; 45 | } 46 | 47 | @GetMapping("/env") 48 | public String env() { 49 | String name = environment.getProperty("name"); 50 | return "Hello," + name; 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/feign/OrderFeignService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.feign; 2 | 3 | import com.leone.cloud.common.entity.Order; 4 | import com.leone.cloud.user.config.FeignConfig; 5 | import feign.HeaderMap; 6 | import feign.Headers; 7 | import feign.Param; 8 | import feign.RequestLine; 9 | import org.springframework.cloud.openfeign.FeignClient; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | /** 16 | * @author Leone 17 | * @since 2018-03-13 18 | **/ 19 | @FeignClient(value = "mc-order", configuration = FeignConfig.class) 20 | public interface OrderFeignService { 21 | 22 | @RequestLine("GET /order/{id}") 23 | Order find(@Param("id") Long id, @HeaderMap Map header); 24 | 25 | @RequestLine("GET /order/list") 26 | @Headers("name-Type: default") 27 | // List list(@QueryMap Map query); 28 | List list(); 29 | 30 | @RequestLine("POST /order") 31 | Order save(@RequestBody Order user); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.service; 2 | 3 | import com.leone.cloud.common.entity.User; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | *

9 | * 10 | * @author Leone 11 | * @since 2018-11-09 12 | **/ 13 | public interface UserService { 14 | 15 | User findOne(Long userId); 16 | 17 | List list(); 18 | } 19 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/java/com/leone/cloud/user/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.user.service.impl; 2 | 3 | 4 | import com.leone.cloud.common.beans.user.UserEditVO; 5 | import com.leone.cloud.common.beans.user.UserVO; 6 | import com.leone.cloud.common.entity.User; 7 | import com.leone.cloud.common.utils.EntityFactory; 8 | import com.leone.cloud.user.service.UserService; 9 | import lombok.extern.slf4j.Slf4j; 10 | import org.springframework.beans.BeanUtils; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.List; 14 | import java.util.Random; 15 | import java.util.stream.Collectors; 16 | 17 | /** 18 | *

19 | * 20 | * @author Leone 21 | * @since 2018-11-09 22 | **/ 23 | @Slf4j 24 | @Service 25 | public class UserServiceImpl implements UserService { 26 | 27 | private Random random = new Random(); 28 | 29 | 30 | // @HystrixCommand(fallbackMethod = "findOneFallback") 31 | @Override 32 | public User findOne(Long userId) { 33 | if (random.nextInt(100) < 1) { 34 | int i = 10 / 0; 35 | } 36 | return EntityFactory.getUser(userId); 37 | } 38 | 39 | 40 | public UserVO findOneFallback(Long userId) { 41 | log.error("findOneFallback userId: {}", userId); 42 | return new UserVO(); 43 | } 44 | 45 | @Override 46 | public List list() { 47 | return EntityFactory.getUsers(10); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9000 3 | 4 | spring: 5 | application: 6 | name: mc-user 7 | servlet: 8 | multipart: 9 | max-file-size: 120MB 10 | max-request-size: 20MB 11 | 12 | eureka: 13 | client: 14 | serviceUrl: 15 | defaultZone: http://localhost:8761/eureka 16 | registry-fetch-interval-seconds: 10 17 | # 是否从eureka中获取信息 注意!!! 18 | fetch-registry: true 19 | # instance: 20 | # 自定义元数据 21 | # metadata-map: 22 | # zone: ABC 23 | # test: BBC 24 | # lease-renewal-interval-in-seconds: 5 25 | # prefer-ip-address: true 26 | # appname: service-user 27 | # hostname: localhost 28 | # status-page-url-path: /health 29 | # namespace: eureka 30 | # 此实例注册到eureka服务端的唯一的实例ID,其组成为${spring.application.name}:${spring.application.instance_id}:${random.value} 31 | # instance-id: ${spring.application.name}:${server.port} 32 | # 获取实例的ip地址 33 | # ip-address: 127.0.0.1 34 | 35 | # 配置负载均衡的规则 36 | #mc-order: 37 | # ribbon: 38 | # NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule 39 | # # 脱离eureka使用 40 | # listOfService: http://localhost:9001,http://localhost:9002 41 | # # 请求连接的超时时间。 42 | # ConnectTimeout: 1000 43 | # # 请求处理的超时时间 44 | # ReadTimeout: 1000 45 | # # 对所以操作请求都进行重试 46 | # OkToRetryOnAllOperations: true 47 | 48 | # 整合 consul 配置 49 | #spring: 50 | # cloud: 51 | # consul: 52 | # enabled: true 53 | # host: localhost 54 | # port: 8500 55 | # discovery: 56 | # # 配置服务注册到Consul上 57 | # register: true # 是否开启在 consul 中注册服务 58 | # health-check-path: /actuator/health #定义 consul 健康检查路径 59 | # health-check-interval: 10s # consul 健康检查频率 60 | # instance-id: ${spring.application.name}:${server.port} # 配置注册到consul 服务的id 61 | # enabled: true #启用 consul 服务发现 62 | # service-name: ${spring.application.name} #设置 注册到 consul 的服务名称 63 | # ip-address: localhost # 访问服务时使用的 ip地址 (还必须设置preferIpAddress才能使用) 64 | # prefer-ip-address: true -------------------------------------------------------------------------------- /spring-cloud-user/src/main/resources/bootstrap.yml: -------------------------------------------------------------------------------- 1 | # zk 配置 2 | #spring: 3 | # cloud: 4 | # zookeeper: 5 | # connect-string: cloud.rm:2181 6 | # discovery: 7 | # enabled: true 8 | # config: 9 | # enable: true 10 | # root: conf 11 | # defaultContext: leone 12 | # profileSeparator: \- 13 | -------------------------------------------------------------------------------- /spring-cloud-user/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Insert title here 6 | 7 | 8 |

9 | File to upload: 10 | 11 | 12 |
13 | 14 | -------------------------------------------------------------------------------- /spring-cloud-zuul/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | spring-cloud-zuul 6 | jar 7 | 8 | 9 | com.leone.cloud 10 | spring-cloud-examples 11 | 2.0.0.RELEASE 12 | 13 | 14 | 15 | UTF-8 16 | 17 | 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-dependencies 23 | 2023.0.3 24 | pom 25 | import 26 | 27 | 28 | org.springframework.boot 29 | spring-boot-dependencies 30 | 3.3.5 31 | pom 32 | import 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | org.springframework.cloud 41 | spring-cloud-starter-netflix-zuul 42 | 2.0.2.RELEASE 43 | 44 | 45 | 46 | org.springframework.cloud 47 | spring-cloud-starter-netflix-eureka-client 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | org.apache.maven.plugins 56 | maven-compiler-plugin 57 | 3.8.0 58 | 59 | 17 60 | 17 61 | UTF-8 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/java/com/leone/cloud/zuul/ZuulApplication.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.zuul; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.zuul.EnableZuulProxy; 7 | 8 | /** 9 | *

10 | * 11 | * @author Leone 12 | * @since 2018-02-10 13 | **/ 14 | @EnableZuulProxy 15 | @EnableDiscoveryClient 16 | @SpringBootApplication 17 | public class ZuulApplication { 18 | public static void main(String[] args) { 19 | SpringApplication.run(ZuulApplication.class, args); 20 | } 21 | 22 | // @Bean 23 | // public PatternServiceRouteMapper serviceRouteMapper() { 24 | // return new PatternServiceRouteMapper( 25 | // "(?^.+)-(?v.+$)", 26 | // "${version}/${name}"); 27 | // } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/java/com/leone/cloud/zuul/filter/ErrorZuulFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.zuul.filter; 2 | 3 | import com.netflix.zuul.ZuulFilter; 4 | import com.netflix.zuul.context.RequestContext; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | *

12 | * 13 | * @author Leone 14 | * @since 2018-02-09 15 | **/ 16 | //@Component 17 | public class ErrorZuulFilter extends ZuulFilter { 18 | 19 | private static final Logger log = LoggerFactory.getLogger(PostZuulFilter.class); 20 | 21 | 22 | /** 23 | * 异常过滤器 24 | * @return 25 | */ 26 | @Override 27 | public String filterType() { 28 | return FilterConstants.ERROR_TYPE; 29 | } 30 | 31 | @Override 32 | public int filterOrder() { 33 | // 优先级,数字越大,优先级越低 34 | return FilterConstants.SEND_ERROR_FILTER_ORDER; 35 | } 36 | 37 | /** 38 | * 是否执行该过滤器,true 代表需要执行 39 | * 40 | * @return 41 | */ 42 | @Override 43 | public boolean shouldFilter() { 44 | return true; 45 | } 46 | 47 | /** 48 | * 主要的处理逻辑的地方,我们做权限控制、日志等都是在这里 49 | * 50 | * @return 51 | */ 52 | @Override 53 | public Object run() { 54 | RequestContext ctx = RequestContext.getCurrentContext(); 55 | ctx.setResponseBody("出现异常"); 56 | log.info("error filter run:{}", ctx.getResponseBody()); 57 | return null; 58 | } 59 | } -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/java/com/leone/cloud/zuul/filter/PostZuulFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.zuul.filter; 2 | 3 | import com.netflix.zuul.ZuulFilter; 4 | import com.netflix.zuul.context.RequestContext; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | *

12 | * 13 | * @author Leone 14 | * @since 2018-02-09 15 | **/ 16 | //@Component 17 | public class PostZuulFilter extends ZuulFilter { 18 | 19 | private static final Logger log = LoggerFactory.getLogger(PostZuulFilter.class); 20 | 21 | /** 22 | * 后置过滤器 23 | * 24 | * @return 25 | */ 26 | @Override 27 | public String filterType() { 28 | return FilterConstants.POST_TYPE; 29 | } 30 | 31 | /** 32 | * filter 执行的优先级,数字越大,优先级越低 33 | * 34 | * @return 35 | */ 36 | @Override 37 | public int filterOrder() { 38 | return FilterConstants.PRE_DECORATION_FILTER_ORDER + 2; 39 | } 40 | 41 | /** 42 | * 是否执行该过滤器,true代表需要过滤 43 | * 44 | * @return 45 | */ 46 | @Override 47 | public boolean shouldFilter() { 48 | return true; 49 | } 50 | 51 | 52 | /** 53 | * 主要的处理逻辑的地方,我们做权限控制、日志等都是在这里 54 | * 55 | * @return 56 | */ 57 | @Override 58 | public Object run() { 59 | RequestContext ctx = RequestContext.getCurrentContext(); 60 | log.info("post filter run... response: {}", ctx.getResponseBody()); 61 | return null; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/java/com/leone/cloud/zuul/filter/PreZuulFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.zuul.filter; 2 | 3 | import com.netflix.zuul.ZuulFilter; 4 | import com.netflix.zuul.context.RequestContext; 5 | import jakarta.servlet.http.HttpServletRequest; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.stereotype.Component; 11 | import org.springframework.util.StringUtils; 12 | 13 | 14 | /** 15 | * @author Leone 16 | * @since 2018-02-07 17 | **/ 18 | //@Component 19 | public class PreZuulFilter extends ZuulFilter { 20 | 21 | private static final Logger log = LoggerFactory.getLogger(PostZuulFilter.class); 22 | 23 | /** 24 | * filter 的类型 前置过滤器 25 | * 26 | * @return 27 | */ 28 | @Override 29 | public String filterType() { 30 | return FilterConstants.PRE_TYPE; 31 | } 32 | 33 | /** 34 | * filter 执行的优先级,数字越大,优先级越低 35 | * 36 | * @return 37 | */ 38 | @Override 39 | public int filterOrder() { 40 | return FilterConstants.PRE_DECORATION_FILTER_ORDER; 41 | } 42 | 43 | /** 44 | * 是否执行该过滤器,true 代表需要执行 45 | * 46 | * @return 47 | */ 48 | @Override 49 | public boolean shouldFilter() { 50 | return false; 51 | } 52 | 53 | /** 54 | * 主要的处理逻辑的地方,我们做权限控制、日志等都是在这里 55 | * 56 | * @return 57 | */ 58 | @Override 59 | public Object run() { 60 | RequestContext requestContext = RequestContext.getCurrentContext(); 61 | //HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); 62 | //String token = request.getParameter("token"); 63 | //String host = request.getRemoteHost(); 64 | //log.info("pre filter run... token: {} host: {}", token, host); 65 | //if (StringUtils.isEmpty(token)) { 66 | // 不响应 request 67 | //requestContext.setSendZuulResponse(false); 68 | //requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); 69 | //} 70 | return null; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/java/com/leone/cloud/zuul/filter/RoutingZuulFilter.java: -------------------------------------------------------------------------------- 1 | package com.leone.cloud.zuul.filter; 2 | 3 | import com.netflix.zuul.ZuulFilter; 4 | import com.netflix.zuul.exception.ZuulException; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; 8 | import org.springframework.stereotype.Component; 9 | 10 | /** 11 | *

12 | * 13 | * @author leone 14 | * @since 2019-01-23 15 | **/ 16 | //@Component 17 | public class RoutingZuulFilter extends ZuulFilter { 18 | 19 | private static final Logger log = LoggerFactory.getLogger(PostZuulFilter.class); 20 | 21 | /** 22 | * 是否执行该过滤器,true 代表需要执行 23 | * 24 | * @return 25 | */ 26 | @Override 27 | public boolean shouldFilter() { 28 | return true; 29 | } 30 | 31 | /** 32 | * filter 执行的优先级,数字越大,优先级越低 33 | * 34 | * @return 35 | */ 36 | @Override 37 | public int filterOrder() { 38 | return FilterConstants.RIBBON_ROUTING_FILTER_ORDER; 39 | } 40 | 41 | 42 | /** 43 | * 主要的处理逻辑的地方,我们做权限控制、日志等都是在这里 44 | * 45 | * @return 46 | */ 47 | @Override 48 | public Object run() throws ZuulException { 49 | log.info("routing filter run..."); 50 | return null; 51 | } 52 | 53 | 54 | /** 55 | * filter 的类型 56 | * 57 | * @return 58 | */ 59 | @Override 60 | public String filterType() { 61 | return FilterConstants.ROUTE_TYPE; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 10000 3 | 4 | spring: 5 | application: 6 | name: mc-zuul 7 | 8 | eureka: 9 | client: 10 | serviceUrl: 11 | defaultZone: http://localhost:8761/eureka 12 | 13 | zuul: 14 | # ignored-patterns: 15 | # - /**/page/** 16 | # 访问 zuul 的前缀 17 | # prefix: /api 18 | # 去掉前缀为 false 默认 true 19 | # strip-prefix: true 20 | # 忽略那些服务 21 | # ignored-services: mc-user 22 | routes: 23 | mc-user: 24 | path: /user/** 25 | serviceId: mc-user 26 | # url: http://localhost:9000 27 | # sensitiveHeaders: Cookie,Set-Cookie,Authorization 28 | order-service: 29 | path: /order/** 30 | serviceId: mc-order 31 | 32 | #ribbon: 33 | # eureka: 34 | # enabled: true 35 | 36 | #mc-user: 37 | # ribbon: 38 | # listOfServers: http://localhost:9001 -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/resources/application.yml1.bak: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: springCloud-gateway-zuul 4 | 5 | server: 6 | port: 8111 7 | 8 | eureka: 9 | client: 10 | service-url: 11 | defaultZone: http://user:password123@localhost:8761/eureka 12 | 13 | zuul: 14 | #忽略所有微服务(除了自定义的微服务) 15 | # ignoredServices: '*' 16 | # ignoredServices: spring-cloud-provider-ribbon-hystrix 17 | #自定义服务名称 18 | routes: 19 | spring-cloud-provider: /user/** 20 | -------------------------------------------------------------------------------- /spring-cloud-zuul/src/main/resources/bootstrap.yml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/janlle/spring-cloud-examples/8f0e0dbb7b9c95dda7920c569657640d25387c18/spring-cloud-zuul/src/main/resources/bootstrap.yml --------------------------------------------------------------------------------