├── .gitattributes ├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── 192.168.192.135.tm0.epoch ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── chengbinbbs │ │ │ ├── SpringBootDataSourceMutilApplication.java │ │ │ ├── config │ │ │ ├── WebMvcConfig.java │ │ │ ├── druid │ │ │ │ ├── DBConfig.java │ │ │ │ ├── DataSourceConfiguration.java │ │ │ │ └── MybatisConfiguration.java │ │ │ └── mybatis │ │ │ │ ├── DataSourceAop.java │ │ │ │ ├── DataSourceContextHolder.java │ │ │ │ ├── DataSourceType.java │ │ │ │ ├── MyAbstractRoutingDataSource.java │ │ │ │ └── MyDataSourceTransactionManager.java │ │ │ ├── controller │ │ │ └── UserController.java │ │ │ ├── mapper │ │ │ └── UserMapper.java │ │ │ ├── model │ │ │ └── User.java │ │ │ ├── service │ │ │ └── UserService.java │ │ │ └── util │ │ │ └── SpringContextHolder.java │ └── resources │ │ ├── application.yml │ │ ├── mapper │ │ └── UserMapper.xml │ │ ├── mybatis-config.xml │ │ └── test.properties └── test │ └── java │ └── com │ └── chengbinbbs │ └── SpringBootDataSourceMutilApplicationTests.java └── tmlog0.log /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chengbinbbs/SpringBootDataSourceMutil/94cae723ce8ebad5dbe37d2765437cae8ad293e2/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /192.168.192.135.tm0.epoch: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringBootDataSourceMutil 2 | 3 | 1.利用Spring的AbstractRoutingDataSource解决多数据源问题 4 | 5 | 2.利用AOP技术实现读写分离 6 | 7 | 3.引入XA分布式事务 8 | 9 | 4.引入Spring-Retry框架,出现网络抖动,连接超时等网络异常时加入重试机制 10 | 11 | 如您觉得该项目对您有用,欢迎点击右上方的Star按钮,给予支持,谢谢!! 12 | -------------------------------------------------------------------------------- /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.chengbinbbs 7 | springbootdatasourcemutil 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | SpringBootDataSourceMutil 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.1.RELEASE 18 | 19 | 20 | 21 | 22 | org.springframework.boot 23 | spring-boot-starter-web 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-tomcat 28 | provided 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-aop 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-configuration-processor 37 | true 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-test 42 | 43 | 44 | 45 | org.springframework.retry 46 | spring-retry 47 | 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-jta-atomikos 53 | 54 | 55 | 56 | 57 | com.fasterxml.jackson.core 58 | jackson-core 59 | 60 | 61 | com.fasterxml.jackson.core 62 | jackson-databind 63 | 64 | 65 | com.fasterxml.jackson.datatype 66 | jackson-datatype-joda 67 | 68 | 69 | com.fasterxml.jackson.module 70 | jackson-module-parameter-names 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-jdbc 76 | 77 | 78 | mysql 79 | mysql-connector-java 80 | 81 | 82 | com.alibaba 83 | druid 84 | 1.0.11 85 | 86 | 87 | 88 | org.mybatis.spring.boot 89 | mybatis-spring-boot-starter 90 | 1.1.1 91 | 92 | 93 | 94 | tk.mybatis 95 | mapper-spring-boot-starter 96 | 1.1.0 97 | 98 | 99 | 100 | com.github.pagehelper 101 | pagehelper-spring-boot-starter 102 | 1.1.0 103 | 104 | 105 | mybatis-spring-boot-starter 106 | org.mybatis.spring.boot 107 | 108 | 109 | 110 | 111 | 112 | 113 | 1.8 114 | 115 | 116 | 117 | 118 | 119 | org.springframework.boot 120 | spring-boot-maven-plugin 121 | 122 | 123 | 124 | 125 | 126 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/SpringBootDataSourceMutilApplication.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.retry.annotation.EnableRetry; 7 | 8 | @EnableRetry 9 | @SpringBootApplication 10 | @MapperScan(basePackages = "com.chengbinbbs.mapper") 11 | public class SpringBootDataSourceMutilApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(SpringBootDataSourceMutilApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/WebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config; 2 | 3 | 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 6 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 7 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 8 | 9 | /**@EnableWebMvc 无需使用该注解,否则会覆盖掉SpringBoot的默认配置值 10 | * @author zhangcb 11 | * @created 2017-07-10 14:12. 12 | */ 13 | @Configuration 14 | public class WebMvcConfig extends WebMvcConfigurerAdapter{ 15 | 16 | /** 17 | * 自定义资源映射 18 | * @param registry 19 | */ 20 | @Override 21 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 22 | registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/"); 23 | super.addResourceHandlers(registry); 24 | } 25 | 26 | /** 27 | * 页面跳转 28 | * @param registry 29 | */ 30 | @Override 31 | public void addViewControllers(ViewControllerRegistry registry) { 32 | registry.addViewController("/login").setViewName("/login"); 33 | registry.addViewController("/chat").setViewName("/chat"); 34 | } 35 | 36 | // @Bean 37 | // public LoginInterceptor loginInterceptor() { 38 | // return new LoginInterceptor(); 39 | // } 40 | 41 | /** 42 | * 添加拦截器 43 | * @param registry 44 | */ 45 | // @Override 46 | // public void addInterceptors(InterceptorRegistry registry) { 47 | // //对所有/order/请求都拦截,但是排除了/toLogin和/login请求的拦截 48 | // registry.addInterceptor(loginInterceptor()).addPathPatterns("/order/**").excludePathPatterns("toLogin","login"); 49 | // } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/druid/DBConfig.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.druid; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.PropertySource; 6 | 7 | /** 8 | * @Author: zhangcb 9 | * @Description: 10 | * @Date: Created on 2017/7/10. 11 | */ 12 | @Configuration 13 | @ConfigurationProperties(prefix = "spring.datasource") 14 | @PropertySource("classpath:test.properties") 15 | public class DBConfig { 16 | private String driverClassName; 17 | private String url; 18 | private String username; 19 | private String password; 20 | /** min-pool-size 最小连接数 **/ 21 | private int minPoolSize; 22 | /** max-pool-size 最大连接数 **/ 23 | private int maxPoolSize; 24 | /** max-lifetime 连接最大存活时间 **/ 25 | private int maxLifetime; 26 | /** borrow-connection-timeout 获取连接失败重新获等待最大时间,在这个时间内如果有可用连接,将返回 **/ 27 | private int borrowConnectionTimeout; 28 | /** login-timeout java数据库连接池,最大可等待获取datasouce的时间 **/ 29 | private int loginTimeout; 30 | /** maintenance-interval 连接回收时间 **/ 31 | private int maintenanceInterval; 32 | /** max-idle-time 最大闲置时间,超过最小连接池连接的连接将将关闭 **/ 33 | private int maxIdleTime; 34 | /** test-query 测试SQL **/ 35 | private String validationQuery; 36 | 37 | public String getDriverClassName() { 38 | return driverClassName; 39 | } 40 | 41 | public void setDriverClassName(String driverClassName) { 42 | this.driverClassName = driverClassName; 43 | } 44 | 45 | public String getUrl() { 46 | return url; 47 | } 48 | 49 | public void setUrl(String url) { 50 | this.url = url; 51 | } 52 | 53 | public String getUsername() { 54 | return username; 55 | } 56 | 57 | public void setUsername(String username) { 58 | this.username = username; 59 | } 60 | 61 | public String getPassword() { 62 | return password; 63 | } 64 | 65 | public void setPassword(String password) { 66 | this.password = password; 67 | } 68 | 69 | public int getMinPoolSize() { 70 | return minPoolSize; 71 | } 72 | 73 | public void setMinPoolSize(int minPoolSize) { 74 | this.minPoolSize = minPoolSize; 75 | } 76 | 77 | public int getMaxPoolSize() { 78 | return maxPoolSize; 79 | } 80 | 81 | public void setMaxPoolSize(int maxPoolSize) { 82 | this.maxPoolSize = maxPoolSize; 83 | } 84 | 85 | public int getMaxLifetime() { 86 | return maxLifetime; 87 | } 88 | 89 | public void setMaxLifetime(int maxLifetime) { 90 | this.maxLifetime = maxLifetime; 91 | } 92 | 93 | public int getBorrowConnectionTimeout() { 94 | return borrowConnectionTimeout; 95 | } 96 | 97 | public void setBorrowConnectionTimeout(int borrowConnectionTimeout) { 98 | this.borrowConnectionTimeout = borrowConnectionTimeout; 99 | } 100 | 101 | public int getLoginTimeout() { 102 | return loginTimeout; 103 | } 104 | 105 | public void setLoginTimeout(int loginTimeout) { 106 | this.loginTimeout = loginTimeout; 107 | } 108 | 109 | public int getMaintenanceInterval() { 110 | return maintenanceInterval; 111 | } 112 | 113 | public void setMaintenanceInterval(int maintenanceInterval) { 114 | this.maintenanceInterval = maintenanceInterval; 115 | } 116 | 117 | public int getMaxIdleTime() { 118 | return maxIdleTime; 119 | } 120 | 121 | public void setMaxIdleTime(int maxIdleTime) { 122 | this.maxIdleTime = maxIdleTime; 123 | } 124 | 125 | public String getValidationQuery() { 126 | return validationQuery; 127 | } 128 | 129 | public void setValidationQuery(String validationQuery) { 130 | this.validationQuery = validationQuery; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/druid/DataSourceConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.druid; 2 | 3 | import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; 4 | import org.apache.commons.logging.Log; 5 | import org.apache.commons.logging.LogFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; 9 | import org.springframework.boot.context.properties.ConfigurationProperties; 10 | import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.context.annotation.Primary; 14 | 15 | import javax.sql.DataSource; 16 | import java.sql.SQLException; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | /** 21 | * Created by zhangcb on 2017/3/6. 22 | */ 23 | @Configuration 24 | public class DataSourceConfiguration { 25 | 26 | private static Log logger = LogFactory.getLog(DataSourceConfiguration.class); 27 | 28 | @Value("${datasource.type}") 29 | private Class dataSourceType; 30 | 31 | // @Bean(name = "writeDataSource", destroyMethod = "close", initMethod="init") 32 | // @Primary 33 | // @ConfigurationProperties(prefix = "datasource.write") 34 | // public DataSource writeDataSource() { 35 | // logger.info("-------------------- writeDataSource init ---------------------"); 36 | // return DataSourceBuilder.create().type(dataSourceType).build(); 37 | // } 38 | 39 | @Bean(name = "writeDataSource", destroyMethod = "close", initMethod="init") 40 | @Primary 41 | public DataSource writeDataSource(@Autowired DBConfig dbConfig) throws SQLException{ 42 | // DruidXADataSource druidXADataSource=new DruidXADataSource(); 43 | // druidXADataSource.setDriverClassName(dbConfig.getDriverClassName()); 44 | // druidXADataSource.setUrl(dbConfig.getUrl()); 45 | // druidXADataSource.setPassword(dbConfig.getPassword()); 46 | // druidXADataSource.setUsername(dbConfig.getUsername()); 47 | MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource(); 48 | mysqlXaDataSource.setUrl(dbConfig.getUrl()); 49 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 50 | mysqlXaDataSource.setPassword(dbConfig.getPassword()); 51 | mysqlXaDataSource.setUser(dbConfig.getUsername()); 52 | mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); 53 | AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean(); 54 | xaDataSource.setXaDataSource(mysqlXaDataSource); 55 | xaDataSource.setUniqueResourceName("writeDataSource"); 56 | 57 | xaDataSource.setMinPoolSize(dbConfig.getMinPoolSize()); 58 | xaDataSource.setMaxPoolSize(dbConfig.getMaxPoolSize()); 59 | xaDataSource.setMaxLifetime(dbConfig.getMaxLifetime()); 60 | xaDataSource.setBorrowConnectionTimeout(dbConfig.getBorrowConnectionTimeout()); 61 | /** login-timeout java数据库连接池,最大可等待获取datasouce的时间 **/ 62 | xaDataSource.setLoginTimeout(dbConfig.getLoginTimeout()); 63 | xaDataSource.setMaintenanceInterval(dbConfig.getMaintenanceInterval()); 64 | xaDataSource.setMaxIdleTime(dbConfig.getMaxIdleTime()); 65 | xaDataSource.setTestQuery(dbConfig.getValidationQuery()); 66 | return xaDataSource; 67 | } 68 | 69 | /** 70 | * 有多少个从库就要配置多少个 71 | * @return 72 | */ 73 | @Bean(name = "readDataSource1") 74 | @ConfigurationProperties(prefix = "datasource.read1") 75 | public DataSource readDataSourceOne() { 76 | logger.info("-------------------- readDataSourceOne init ---------------------"); 77 | return DataSourceBuilder.create().type(dataSourceType).build(); 78 | } 79 | 80 | @Bean(name = "readDataSource2") 81 | @ConfigurationProperties(prefix = "datasource.read2") 82 | public DataSource readDataSourceTwo() { 83 | logger.info("-------------------- readDataSourceTwo init ---------------------"); 84 | return DataSourceBuilder.create().type(dataSourceType).build(); 85 | } 86 | 87 | @Bean("readDataSources") 88 | public List readDataSources(){ 89 | List dataSources=new ArrayList<>(); 90 | dataSources.add(readDataSourceOne()); 91 | dataSources.add(readDataSourceTwo()); 92 | return dataSources; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/druid/MybatisConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.druid; 2 | 3 | import com.chengbinbbs.config.mybatis.DataSourceType; 4 | import com.chengbinbbs.config.mybatis.MyAbstractRoutingDataSource; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.apache.ibatis.session.SqlSessionFactory; 8 | import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 11 | import org.springframework.context.annotation.Bean; 12 | import org.springframework.context.annotation.Configuration; 13 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 14 | 15 | import javax.annotation.Resource; 16 | import javax.sql.DataSource; 17 | import java.util.HashMap; 18 | import java.util.List; 19 | import java.util.Map; 20 | 21 | /** 22 | * Created by zhangcb on 2017/3/6. 23 | */ 24 | @Configuration 25 | @AutoConfigureAfter({DataSourceConfiguration.class}) 26 | public class MybatisConfiguration extends MybatisAutoConfiguration { 27 | 28 | private static Log logger = LogFactory.getLog(MybatisConfiguration.class); 29 | 30 | @Value("${datasource.readSize}") 31 | private String dataSourceSize; 32 | 33 | @Resource(name = "writeDataSource") 34 | private DataSource writeDataSource; 35 | 36 | @Resource(name = "readDataSources") 37 | private List readDataSources; 38 | 39 | @Bean 40 | public SqlSessionFactory sqlSessionFactorys() throws Exception { 41 | logger.info("-------------------- 重载父类 sqlSessionFactory init ---------------------"); 42 | return super.sqlSessionFactory(roundRobinDataSouceProxy()); 43 | } 44 | 45 | /** 46 | * 有多少个数据源就要配置多少个bean 47 | * @return 48 | */ 49 | @Bean 50 | public AbstractRoutingDataSource roundRobinDataSouceProxy() { 51 | int size = Integer.parseInt(dataSourceSize); 52 | MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource(size); 53 | Map targetDataSources = new HashMap(); 54 | // 写 55 | targetDataSources.put(DataSourceType.write.getType(), writeDataSource); 56 | 57 | for (int i = 0; i < size; i++) { 58 | targetDataSources.put(i, readDataSources.get(i)); 59 | } 60 | proxy.setDefaultTargetDataSource(writeDataSource); 61 | proxy.setTargetDataSources(targetDataSources); 62 | return proxy; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/mybatis/DataSourceAop.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.mybatis; 2 | 3 | import org.apache.commons.logging.Log; 4 | import org.apache.commons.logging.LogFactory; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.annotation.Before; 7 | import org.springframework.stereotype.Component; 8 | 9 | /** 10 | * @author zhangcb 11 | * @created 2017-07-10 17:34. 12 | */ 13 | @Aspect 14 | @Component 15 | public class DataSourceAop { 16 | 17 | private static Log logger = LogFactory.getLog(DataSourceAop.class); 18 | 19 | @Before("execution(* com.chengbinbbs.mapper..*.find*(..)) || execution(* com.chengbinbbs.mapper..*.get*(..))") 20 | public void setReadDataSourceType() { 21 | DataSourceContextHolder.read(); 22 | logger.info("dataSource切换到:Read"); 23 | } 24 | 25 | @Before("execution(* com.chengbinbbs.mapper..*.insert*(..)) || execution(* com.chengbinbbs.mapper..*.insert*(..)) || execution(* com.chengbinbbs.mapper..*.update*(..))") 26 | public void setWriteDataSourceType() { 27 | DataSourceContextHolder.write(); 28 | logger.info("dataSource切换到:write"); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/mybatis/DataSourceContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.mybatis; 2 | 3 | /** 4 | * @author zhangcb 5 | * @created 2017-07-10 17:30. 6 | */ 7 | public class DataSourceContextHolder { 8 | private static final ThreadLocal local = new ThreadLocal(); 9 | 10 | public static ThreadLocal getLocal() { 11 | return local; 12 | } 13 | 14 | /** 15 | * 读可能是多个库 16 | */ 17 | public static void read() { 18 | local.set(DataSourceType.read.getType()); 19 | } 20 | 21 | /** 22 | * 写只有一个库 23 | */ 24 | public static void write() { 25 | local.set(DataSourceType.write.getType()); 26 | } 27 | 28 | public static String getJdbcType() { 29 | return local.get(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/mybatis/DataSourceType.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.mybatis; 2 | 3 | /** 4 | * @author zhangcb 5 | * @created on 2017-07-10 17:30. 6 | */ 7 | public enum DataSourceType { 8 | read("read", "从库"), write("write", "主库"); 9 | 10 | private String type; 11 | 12 | private String name; 13 | 14 | public String getType() { 15 | return type; 16 | } 17 | 18 | public void setType(String type) { 19 | this.type = type; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | DataSourceType(String type, String name) { 31 | this.type = type; 32 | this.name = name; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/mybatis/MyAbstractRoutingDataSource.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.mybatis; 2 | 3 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | /** 8 | * @author zhangcb 9 | * @created 2017-07-10 17:33. 10 | */ 11 | public class MyAbstractRoutingDataSource extends AbstractRoutingDataSource { 12 | private final int dataSourceNumber; 13 | private AtomicInteger count = new AtomicInteger(0); 14 | 15 | public MyAbstractRoutingDataSource(int dataSourceNumber) { 16 | this.dataSourceNumber = dataSourceNumber; 17 | } 18 | 19 | @Override 20 | protected Object determineCurrentLookupKey() { 21 | String typeKey = DataSourceContextHolder.getJdbcType(); 22 | if (typeKey.equals(DataSourceType.write.getType())) 23 | return DataSourceType.write.getType(); 24 | // 读 简单负载均衡 25 | int number = count.getAndAdd(1); 26 | int lookupKey = number % dataSourceNumber; 27 | return new Integer(lookupKey); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/config/mybatis/MyDataSourceTransactionManager.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.config.mybatis; 2 | 3 | import com.atomikos.icatch.jta.UserTransactionImp; 4 | import com.atomikos.icatch.jta.UserTransactionManager; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.DependsOn; 11 | import org.springframework.transaction.PlatformTransactionManager; 12 | import org.springframework.transaction.annotation.EnableTransactionManagement; 13 | import org.springframework.transaction.jta.JtaTransactionManager; 14 | 15 | import javax.transaction.TransactionManager; 16 | import javax.transaction.UserTransaction; 17 | 18 | /** 19 | * @author zhangcb 20 | * @created 2017-07-10 17:37. 21 | */ 22 | @Configuration 23 | @EnableTransactionManagement 24 | public class MyDataSourceTransactionManager extends DataSourceTransactionManagerAutoConfiguration { 25 | 26 | private static Log logger = LogFactory.getLog(MyDataSourceTransactionManager.class); 27 | 28 | /** 29 | * 自定义事务 30 | * MyBatis自动参与到spring事务管理中,无需额外配置,只要org.mybatis.spring.SqlSessionFactoryBean引用的数据源与DataSourceTransactionManager引用的数据源一致即可,否则事务管理会不起作用。 31 | * @return 32 | */ 33 | // @Resource(name = "writeDataSource") 34 | // private DataSource dataSource; 35 | // 36 | // @Bean(name = "transactionManager") 37 | // public DataSourceTransactionManager transactionManagers() { 38 | // logger.info("-------------------- transactionManager init ---------------------"); 39 | // return new DataSourceTransactionManager(dataSource); 40 | // } 41 | 42 | /** 43 | * 分布式XA事务 44 | * @return 45 | * @throws Throwable 46 | */ 47 | @Bean(name = "userTransaction") 48 | public UserTransaction userTransaction() throws Throwable { 49 | UserTransactionImp userTransactionImp = new UserTransactionImp(); 50 | userTransactionImp.setTransactionTimeout(10000); 51 | return userTransactionImp; 52 | } 53 | @Bean(name = "atomikosTransactionManager", initMethod = "init", destroyMethod = "close") 54 | public TransactionManager atomikosTransactionManager() throws Throwable { 55 | UserTransactionManager userTransactionManager = new UserTransactionManager(); 56 | userTransactionManager.setForceShutdown(false); 57 | return userTransactionManager; 58 | } 59 | @Bean(name = "transactionManager") 60 | @DependsOn({ "userTransaction", "atomikosTransactionManager" }) 61 | public PlatformTransactionManager transactionManager() throws Throwable { 62 | UserTransaction userTransaction = userTransaction(); 63 | JtaTransactionManager manager = new JtaTransactionManager(userTransaction,atomikosTransactionManager()); 64 | return manager; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.controller; 2 | 3 | import com.chengbinbbs.model.User; 4 | import com.chengbinbbs.service.UserService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.validation.BindingResult; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import javax.validation.Valid; 12 | 13 | /** 14 | * 用户中心 15 | * 16 | * @author zhangcb 17 | * @created 2017-07-10 17:37. 18 | */ 19 | @RestController 20 | public class UserController { 21 | 22 | @Autowired 23 | private UserService userInfoService; 24 | 25 | @RequestMapping("/hello") 26 | public String hello(){ 27 | return "hello"; 28 | } 29 | 30 | @RequestMapping("/user/{name}") 31 | public User findByName(@PathVariable String name){ 32 | return userInfoService.findByUserName(name); 33 | } 34 | 35 | @RequestMapping("/user/add") 36 | public int addUser(@Valid User user, BindingResult result){ 37 | if(result.hasErrors()){ 38 | System.out.println("添加用户异常"); 39 | return -1; 40 | } 41 | return userInfoService.save(user); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/mapper/UserMapper.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.mapper; 2 | 3 | 4 | import com.chengbinbbs.model.User; 5 | 6 | /** 7 | * @author zhangcb 8 | * @created on 2017/5/15. 9 | */ 10 | public interface UserMapper { 11 | 12 | User findByUserName(String name); 13 | 14 | public int insert(User user); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/model/User.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.model; 2 | 3 | import org.hibernate.validator.constraints.NotEmpty; 4 | 5 | import javax.validation.constraints.Max; 6 | import javax.validation.constraints.Min; 7 | import java.io.Serializable; 8 | 9 | /** 10 | * 用户实体类 11 | * 12 | * @author zhangcb 13 | * @created 2017-05-23 10:34. 14 | */ 15 | public class User implements Serializable { 16 | 17 | private Long id; 18 | 19 | @NotEmpty(message="姓名不能为空") 20 | private String name; 21 | 22 | @Max(value = 100, message = "年龄不能大于100岁") 23 | @Min(value= 18 ,message= "必须年满18岁!" ) 24 | private Integer age; 25 | 26 | public User() { 27 | } 28 | 29 | public User(String name, Integer age) { 30 | this.name = name; 31 | this.age = age; 32 | } 33 | 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public Integer getAge() { 51 | return age; 52 | } 53 | 54 | public void setAge(Integer age) { 55 | this.age = age; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.service; 2 | 3 | import com.chengbinbbs.mapper.UserMapper; 4 | import com.chengbinbbs.model.User; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.retry.annotation.Backoff; 7 | import org.springframework.retry.annotation.Recover; 8 | import org.springframework.retry.annotation.Retryable; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | /** 13 | * 用户服务实现 14 | * 15 | * @author zhangcb 16 | * @created 2017-07-10 10:35. 17 | */ 18 | @Service("userInfoService") 19 | public class UserService { 20 | int i=1; 21 | @Autowired 22 | private UserMapper userMapper; 23 | 24 | public User findByUserName(String name) { 25 | return userMapper.findByUserName(name); 26 | } 27 | 28 | /** 29 | * @Retryable:标注此注解的方法在发生异常时会进行重试 30 | 参数说明:value:抛出指定异常才会重试 31 | include:和value一样,默认为空,当exclude也为空时,默认所以异常 32 | exclude:指定不处理的异常 33 | maxAttempts:最大重试次数,默认3次 34 | backoff:重试等待策略,默认使用@Backoff,@Backoff的value默认为1000L,multiplier(指定延迟倍数) 35 | 默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为2,则第一次重试为1秒,第二次为 36 | 2秒,第三次为4秒 37 | * @param user 38 | * @return 39 | */ 40 | @Retryable(value = {RuntimeException.class},maxAttempts = 4,backoff = @Backoff(delay = 1000l,multiplier = 1)) 41 | public int insert(User user) { 42 | userMapper.insert(user); 43 | throw new RuntimeException("插入异常!"); 44 | } 45 | 46 | //@Recover:用于@Retryable重试失败后处理方法,此方法里的异常一定要是@Retryable方法里抛出的异常,否则不会调用这个方法 47 | @Recover 48 | public Integer recover(RuntimeException e){ 49 | return 6; 50 | } 51 | 52 | @Transactional 53 | public int save(User user) { 54 | userMapper.insert(user); 55 | //模拟事务异常回滚 56 | throw new RuntimeException("插入异常!"); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/chengbinbbs/util/SpringContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.beans.factory.NoSuchBeanDefinitionException; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.context.ApplicationContextAware; 7 | 8 | /** 9 | * 用于取得 spring 的 bean 定义. 10 | *
需要在 content-hibernate.xml中加上:
 11 |  * <bean id="SpringContextUtil " class="SpringContextUtil " scope="singleton" />
 12 |  * 当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
 13 |  * 
14 | * @author Watson 15 | * @since 4.0 16 | */ 17 | 18 | public class SpringContextHolder implements ApplicationContextAware { 19 | 20 | //Spring应用上下文环境 21 | private static ApplicationContext applicationContext; 22 | 23 | /** 24 | * 实现ApplicationContextAware接口的回调方法,设置上下文环境 25 | * 26 | * @param applicationContext 27 | * @throws BeansException 28 | */ 29 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 30 | SpringContextHolder.applicationContext = applicationContext; 31 | } 32 | 33 | /** 34 | * @return ApplicationContext 35 | */ 36 | public static ApplicationContext getApplicationContext() { 37 | return applicationContext; 38 | } 39 | 40 | /** 41 | * 获取对象 42 | * 43 | * @param name 44 | * @return Object 一个以所给名字注册的bean的实例 45 | * @throws BeansException 46 | */ 47 | public static Object getBean(String name) throws BeansException { 48 | return applicationContext.getBean(name); 49 | } 50 | 51 | /** 52 | * 获取类型为requiredType的对象 53 | * 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException) 54 | * 55 | * @param name bean注册名 56 | * @param requiredType 返回对象类型 57 | * @return Object 返回requiredType类型对象 58 | * @throws BeansException 59 | */ 60 | public static T getBean(String name, Class requiredType) throws BeansException { 61 | return applicationContext.getBean(name, requiredType); 62 | } 63 | 64 | /** 65 | * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true 66 | * 67 | * @param name 68 | * @return boolean 69 | */ 70 | public static boolean containsBean(String name) { 71 | return applicationContext.containsBean(name); 72 | } 73 | 74 | /** 75 | * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 76 | * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) 77 | * 78 | * @param name 79 | * @return boolean 80 | * @throws NoSuchBeanDefinitionException 81 | */ 82 | public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { 83 | return applicationContext.isSingleton(name); 84 | } 85 | 86 | /** 87 | * @param name 88 | * @return Class 注册对象的类型 89 | * @throws NoSuchBeanDefinitionException 90 | */ 91 | public static Class getType(String name) throws NoSuchBeanDefinitionException { 92 | return applicationContext.getType(name); 93 | } 94 | 95 | /** 96 | * 如果给定的bean名字在bean定义中有别名,则返回这些别名 97 | * 98 | * @param name 99 | * @return 100 | * @throws NoSuchBeanDefinitionException 101 | */ 102 | public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { 103 | return applicationContext.getAliases(name); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9090 3 | #字符编码 Request 和 Response 强制设为UTF-8 4 | spring: 5 | http: 6 | encoding: 7 | charset: UTF-8 8 | enabled: true 9 | force: true 10 | #日志颜色 11 | output: 12 | ansi: 13 | enabled: ALWAYS 14 | logging: 15 | level: 16 | tk.mybatis: TRACE 17 | #多数据源 1主2从 18 | datasource: 19 | #从库数量 20 | readSize: 2 21 | # 使用druid数据源 22 | type: com.alibaba.druid.pool.DruidDataSource 23 | #主库 24 | write: 25 | url: jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8 26 | username: root 27 | password: root 28 | driver-class-name: com.mysql.jdbc.Driver 29 | filters: stat 30 | maxActive: 20 31 | initialSize: 1 32 | maxWait: 60000 33 | minIdle: 1 34 | timeBetweenEvictionRunsMillis: 60000 35 | minEvictableIdleTimeMillis: 300000 36 | validationQueryTimeout: 900000 37 | validationQuery: SELECT SYSDATE() from dual 38 | testWhileIdle: true 39 | testOnBorrow: false 40 | testOnReturn: false 41 | poolPreparedStatements: true 42 | maxOpenPreparedStatements: 20 43 | read1: 44 | url: jdbc:mysql://localhost:3306/slave1?useUnicode=true&characterEncoding=utf-8 45 | username: root 46 | password: root 47 | driver-class-name: com.mysql.jdbc.Driver 48 | filters: stat 49 | maxActive: 20 50 | initialSize: 1 51 | maxWait: 60000 52 | minIdle: 1 53 | timeBetweenEvictionRunsMillis: 60000 54 | minEvictableIdleTimeMillis: 300000 55 | validationQueryTimeout: 900000 56 | validationQuery: SELECT SYSDATE() from dual 57 | testWhileIdle: true 58 | testOnBorrow: false 59 | testOnReturn: false 60 | poolPreparedStatements: true 61 | maxOpenPreparedStatements: 20 62 | read2: 63 | url: jdbc:mysql://localhost:3306/slave2?useUnicode=true&characterEncoding=utf-8 64 | username: root 65 | password: root 66 | driver-class-name: com.mysql.jdbc.Driver 67 | filters: stat 68 | maxActive: 20 69 | initialSize: 1 70 | maxWait: 60000 71 | minIdle: 1 72 | timeBetweenEvictionRunsMillis: 60000 73 | minEvictableIdleTimeMillis: 300000 74 | validationQueryTimeout: 900000 75 | validationQuery: SELECT SYSDATE() from dual 76 | testWhileIdle: true 77 | testOnBorrow: false 78 | testOnReturn: false 79 | poolPreparedStatements: true 80 | maxOpenPreparedStatements: 20 81 | 82 | mybatis: 83 | type-aliases-package: com.chengbinbbs.model 84 | mapper-locations: classpath:mapper/*.xml 85 | config-location: classpath:mybatis-config.xml 86 | 87 | pagehelper: 88 | helperDialect: mysql 89 | reasonable: true 90 | supportMethodsArguments: true 91 | params: count=countSql -------------------------------------------------------------------------------- /src/main/resources/mapper/UserMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | id, name, age 12 | 13 | 14 | 20 | 21 | 22 | insert into user (id, name, age 23 | ) 24 | values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER} 25 | ) 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/resources/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 46 | 47 | 48 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/resources/test.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 | spring.datasource.url=jdbc:mysql://localhost:3306/master 3 | spring.datasource.username=root 4 | spring.datasource.password=root 5 | 6 | spring.datasource.minPoolSize = 3 7 | spring.datasource.maxPoolSize = 25 8 | spring.datasource.maxLifetime = 20000 9 | spring.datasource.borrowConnectionTimeout = 30 10 | spring.datasource.loginTimeout = 30 11 | spring.datasource.maintenanceInterval = 60 12 | spring.datasource.maxIdleTime = 60 13 | spring.datasource.validationQuery = select 1 -------------------------------------------------------------------------------- /src/test/java/com/chengbinbbs/SpringBootDataSourceMutilApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.chengbinbbs; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringBootDataSourceMutilApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /tmlog0.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chengbinbbs/SpringBootDataSourceMutil/94cae723ce8ebad5dbe37d2765437cae8ad293e2/tmlog0.log --------------------------------------------------------------------------------