├── .github └── workflows │ └── gradle.yml ├── .gitignore ├── Issues.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main ├── java │ └── cn │ │ └── com │ │ └── hellowood │ │ └── dynamicdatasource │ │ ├── DynamicDataSourceApplication.java │ │ ├── apiutil │ │ ├── annotation │ │ │ └── ApiResponseBody.java │ │ ├── config │ │ │ └── BaseWebMvcConfig.java │ │ ├── exception │ │ │ ├── BaseExceptionHandler.java │ │ │ ├── CustomServiceException.java │ │ │ └── enums │ │ │ │ └── CustomExceptionEnum.java │ │ ├── interceptor │ │ │ └── ApiResponseBodyReturnValueHandler.java │ │ └── model │ │ │ └── BaseResponse.java │ │ ├── common │ │ ├── CommonConstant.java │ │ ├── CommonResponse.java │ │ ├── DataSourceKey.java │ │ ├── ResponseCode.java │ │ └── ResponseUtil.java │ │ ├── configuration │ │ ├── CustomHandlerExceptionResolver.java │ │ ├── DataSourceConfigurer.java │ │ ├── DynamicDataSourceAspect.java │ │ ├── DynamicDataSourceContextHolder.java │ │ ├── DynamicRoutingDataSource.java │ │ └── WebMvcConfigurer.java │ │ ├── controller │ │ ├── BaseController.java │ │ └── ProductController.java │ │ ├── error │ │ └── ServiceException.java │ │ ├── mapper │ │ └── ProductDao.java │ │ ├── model │ │ └── Product.java │ │ ├── service │ │ └── ProductService.java │ │ └── utils │ │ ├── ApplicationContextHolder.java │ │ ├── HttpLog.java │ │ └── JSONUtil.java └── resources │ ├── application.properties │ ├── db │ └── schema.sql │ └── mappers │ └── ProductMapper.xml └── test └── java └── cn └── com └── hellowood └── dynamicdatasource └── DynamicDataSourceApplicationTests.java /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: Set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | - name: Build with Gradle 17 | run: ./gradlew clean build -x test 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | 4 | 5 | ### IntelliJ IDEA ### 6 | .idea 7 | *.iml 8 | 9 | build/ 10 | 11 | ### Java template 12 | # Compiled class file 13 | *.class 14 | 15 | # Log file 16 | *.log 17 | 18 | out/ 19 | logs/ -------------------------------------------------------------------------------- /Issues.md: -------------------------------------------------------------------------------- 1 | # 在使用 Spring Boot 和 MyBatis 动态切换数据源时遇到的问题以及解决方法 2 | 3 | > 相关项目地址:[https://github.com/helloworlde/SpringBoot-DynamicDataSource](https://github.com/helloworlde/SpringBoot-DynamicDataSource) 4 | 5 | ## 1. org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 6 | 7 | > 在使用了动态数据源后遇到了该问题,从错误信息来看是因为没有找到 `*.xml` 文件而导致的,但是在配置文件中 8 | 确实添加了相关的配置,这种错误的原因是因为设置数据源后没有设置`SqlSessionFactoryBean`的 `typeAliasesPackage` 9 | 和`mapperLocations`属性或属性无效导致的; 10 | 11 | - 解决方法: 12 | 13 | > 如果在应用的入口类中添加了 `@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)`, 14 | 在`DataSourceConfigure`类的中设置相关属性: 15 | 16 | ```java 17 | @Bean 18 | @ConfigurationProperties(prefix = "mybatis") 19 | public SqlSessionFactoryBean sqlSessionFactoryBean() { 20 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 21 | sqlSessionFactoryBean.setDataSource(dynamicDataSource()); 22 | return sqlSessionFactoryBean; 23 | } 24 | ``` 25 | 26 | 或者直接配置(不推荐该方式): 27 | 28 | ```java 29 | @Bean 30 | public SqlSessionFactoryBean sqlSessionFactoryBean() { 31 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 32 | sqlSessionFactoryBean.setTypeAliasesPackage("typeAliasesPackage"); 33 | sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapperLocations")); 34 | sqlSessionFactoryBean.setDataSource(dynamicDataSource()); 35 | return sqlSessionFactoryBean; 36 | } 37 | ``` 38 | 39 | 40 | 41 | 42 | 43 | ## 2. Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed 44 | 45 | > 该异常在错误信息中已经说的很清楚了,是因为有多个 `DataSource` 的实例,所以无法确定该引用那个实例 46 | 47 | - 解决方法: 48 | 49 | > 为数据源的某个 `Bean` 添加 `@Primary` 注解,该 `Bean` 应当是通过 `DataSourceBuilder.create().build()` 50 | 得到的 `Bean`,而不是通过 `new AbstractRoutingDataSource` 的子类实现的 `Bean`,在本项目中可以是 `master()` 51 | 或 `slave()` 得到的 `DataSource`,不能是 `dynamicDataSource()` 得到的 `DataSource` 52 | 53 | ## 3. 通过注解方式动态切换数据源无效 54 | 55 | - 请确认注解没有放到 DAO 层方法上, 因为会在 Service 层开启事务,所以当注解在 DAO 层时不会生效 56 | - 请确认以下 `Bean` 正确配置: 57 | 58 | ```java 59 | @Bean("dynamicDataSource") 60 | public DataSource dynamicDataSource() { 61 | DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); 62 | Map dataSourceMap = new HashMap<>(2); 63 | dataSourceMap.put("master", master()); 64 | dataSourceMap.put("slave", slave()); 65 | 66 | // Set master datasource as default 67 | dynamicRoutingDataSource.setDefaultTargetDataSource(master()); 68 | // Set master and slave datasource as target datasource 69 | dynamicRoutingDataSource.setTargetDataSources(dataSourceMap); 70 | 71 | // To put datasource keys into DataSourceContextHolder to judge if the datasource is exist 72 | DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet()); 73 | return dynamicRoutingDataSource; 74 | } 75 | 76 | @Bean 77 | @ConfigurationProperties(prefix = "mybatis") 78 | public SqlSessionFactoryBean sqlSessionFactoryBean() { 79 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 80 | // Here is very important, if don't config this, will can't switch datasource 81 | // put all datasource into SqlSessionFactoryBean, then will autoconfig SqlSessionFactory 82 | sqlSessionFactoryBean.setDataSource(dynamicDataSource()); 83 | return sqlSessionFactoryBean; 84 | } 85 | 86 | ``` 87 | 88 | ## 4. `@Transactional` 注解无效,发生异常不回滚 89 | 90 | - 请确认该 `Bean` 得到正确配置,并且`@Transactional` 的 `rollbackFor` 配置正确 91 | 92 | ```java 93 | @Bean 94 | public PlatformTransactionManager transactionManager() { 95 | return new DataSourceTransactionManager(dynamicDataSource()); 96 | } 97 | 98 | ``` 99 | 100 | ## 5. 通过 AOP 判断 DAO 层方法名时切换数据源无效 101 | 102 | > 当切面指向了 DAO 层后无论如何设置切面的顺序,都无法在执行查询之前切换数据源,但是切面改为 Service 层后可以正常工作 103 | 104 | - 解决方法: 请确认 `@Transactional` 注解是加在方法上而不是 Service 类上,添加了 `@Transactional` 的方法因为在 Service 层开启了事务, 105 | 会在事务结束之后才会切换数据源 106 | 107 | - 检出 `DataSourceTransactionManager` Bean 注入正确 108 | 109 | ```java 110 | @Bean 111 | public PlatformTransactionManager transactionManager() { 112 | return new DataSourceTransactionManager(dynamicDataSource()); 113 | } 114 | ``` 115 | 116 | ## 6. The dependencies of some of the beans in the application context form a cycle 117 | 118 | - 错误信息: 119 | 120 | ``` 121 | The dependencies of some of the beans in the application context form a cycle: 122 | 123 | produceController (field private cn.com.hellowood.dynamicdatasource.service.ProductService cn.com.hellowood.dynamicdatasource.controller.ProduceController.productService) 124 | ↓ 125 | productService (field private cn.com.hellowood.dynamicdatasource.mapper.ProductDao cn.com.hellowood.dynamicdatasource.service.ProductService.productDao) 126 | ↓ 127 | productDao defined in file [/Users/hellowoodes/Downloads/Dev/SpringBoot/DynamicDataSource/out/production/classes/cn/com/hellowood/dynamicdatasource/mapper/ProductDao.class] 128 | ↓ 129 | sqlSessionFactoryBean defined in class path resource [cn/com/hellowood/dynamicdatasource/configuration/DataSourceConfigurer.class] 130 | ┌─────┐ 131 | | dynamicDataSource defined in class path resource [cn/com/hellowood/dynamicdatasource/configuration/DataSourceConfigurer.class] 132 | ↑ ↓ 133 | | master defined in class path resource [cn/com/hellowood/dynamicdatasource/configuration/DataSourceConfigurer.class] 134 | ↑ ↓ 135 | | dataSourceInitializer 136 | └─────┘ 137 | ``` 138 | 139 | > 这是因为在注入 `DataSource` 的实例的时候产生了循环调用,第一个注入的 Bean 依赖于其他的 Bean, 而被依赖的 Bean 产生依赖传递,依赖第一个 140 | 注入的 Bean, 陷入了循环,无法启动项目 141 | 142 | - 解决方法:将 `@Primary` 注解指向没有依赖的 Bean,如: 143 | ```java 144 | 145 | /** 146 | * master DataSource 147 | * @Primary 注解用于标识默认使用的 DataSource Bean,因为有三个 DataSource Bean,该注解可用于 master 148 | * 或 slave DataSource Bean, 但不能用于 dynamicDataSource Bean, 否则会产生循环调用 149 | * 150 | * @ConfigurationProperties 注解用于从 application.properties 文件中读取配置,为 Bean 设置属性 151 | * @return data source 152 | */ 153 | @Bean("master") 154 | @Primary 155 | @ConfigurationProperties(prefix = "application.server.db.master") 156 | public DataSource master() { 157 | return DataSourceBuilder.create().build(); 158 | } 159 | 160 | @Bean("slave") 161 | @ConfigurationProperties(prefix = "application.server.db.slave") 162 | public DataSource slave() { 163 | return DataSourceBuilder.create().build(); 164 | } 165 | 166 | @Bean("dynamicDataSource") 167 | public DataSource dynamicDataSource() { 168 | DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); 169 | Map dataSourceMap = new HashMap<>(2); 170 | dataSourceMap.put("master", master()); 171 | dataSourceMap.put("slave", slave()); 172 | 173 | // Set master datasource as default 174 | dynamicRoutingDataSource.setDefaultTargetDataSource(master()); 175 | // Set master and slave datasource as target datasource 176 | dynamicRoutingDataSource.setTargetDataSources(dataSourceMap); 177 | 178 | // To put datasource keys into DataSourceContextHolder to judge if the datasource is exist 179 | DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet()); 180 | return dynamicRoutingDataSource; 181 | } 182 | ``` 183 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot 和 MyBatis 实现多数据源、动态数据源切换 2 | 3 | - **[多数据源分布式事务](https://github.com/helloworlde/spring-cloud-alibaba-component/tree/master/cloud-seata-multi-datasource): 使用 [Seata](https://github.com/seata/seata) 实现的多数据源事务** 4 | 5 | ### 在使用的过程中基本踩遍了所有动态数据源切换的坑,将常见的一些坑和解决方法写在了 [Issues](https://github.com/helloworlde/SpringBoot-DynamicDataSource/blob/master/Issues.md) 里面 6 | 7 | 8 | > 该项目使用了一个可写数据源和多个只读数据源,为了减少数据库压力,使用轮循的方式选择只读数据源;考虑到在一个 Service 中同时会有读和写的操作,所以本应用使用 AOP 切面通过 DAO 层的方法名切换只读数据源;但这种方式要求数据源主从一致,并且应当避免在同一个 Service 方法中写入后立即查询,如果必须在执行写入操作后立即读取,应当在 Service 方法上添加 `@Transactional` 注解以保证使用主数据源 9 | 10 | > 需要注意的是,使用 DAO 层切面后不应该在 Service 类层面上加 `@Transactional` 注解,而应该添加在方法上,这也是 Spring 推荐的做法 11 | 12 | > 动态切换数据源依赖 `configuration` 包下的4个类来实现,分别是: 13 | > - DataSourceRoutingDataSource.java 14 | > - DataSourceConfigurer.java 15 | > - DynamicDataSourceContextHolder.java 16 | > - DynamicDataSourceAspect.java 17 | 18 | --------------------- 19 | 20 | ## 添加依赖 21 | ```groovy 22 | dependencies { 23 | compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2') 24 | compile('org.springframework.boot:spring-boot-starter-web') 25 | compile('org.springframework.boot:spring-boot-starter-aop') 26 | runtime('mysql:mysql-connector-java') 27 | testCompile('org.springframework.boot:spring-boot-starter-test') 28 | } 29 | ``` 30 | 31 | ## 创建数据库及表 32 | 33 | - 分别创建数据库`product_master`, `product_slave_alpha`, `product_slave_beta`, `product_slave_gamma` 34 | - 在以上数据库中分别创建表 `product`,并插入不同数据 35 | 36 | ```sql 37 | DROP DATABASE IF EXISTS product_master; 38 | CREATE DATABASE product_master; 39 | CREATE TABLE product_master.product( 40 | id INT PRIMARY KEY AUTO_INCREMENT, 41 | name VARCHAR(50) NOT NULL, 42 | price DOUBLE(10,2) NOT NULL DEFAULT 0); 43 | INSERT INTO product_master.product (name, price) VALUES('master', '1'); 44 | 45 | 46 | DROP DATABASE IF EXISTS product_slave_alpha; 47 | CREATE DATABASE product_slave_alpha; 48 | CREATE TABLE product_slave_alpha.product( 49 | id INT PRIMARY KEY AUTO_INCREMENT, 50 | name VARCHAR(50) NOT NULL, 51 | price DOUBLE(10,2) NOT NULL DEFAULT 0); 52 | INSERT INTO product_slave_alpha.product (name, price) VALUES('slaveAlpha', '1'); 53 | 54 | DROP DATABASE IF EXISTS product_slave_beta; 55 | CREATE DATABASE product_slave_beta; 56 | CREATE TABLE product_slave_beta.product( 57 | id INT PRIMARY KEY AUTO_INCREMENT, 58 | name VARCHAR(50) NOT NULL, 59 | price DOUBLE(10,2) NOT NULL DEFAULT 0); 60 | INSERT INTO product_slave_beta.product (name, price) VALUES('slaveBeta', '1'); 61 | 62 | DROP DATABASE IF EXISTS product_slave_gamma; 63 | CREATE DATABASE product_slave_gamma; 64 | CREATE TABLE product_slave_gamma.product( 65 | id INT PRIMARY KEY AUTO_INCREMENT, 66 | name VARCHAR(50) NOT NULL, 67 | price DOUBLE(10,2) NOT NULL DEFAULT 0); 68 | INSERT INTO product_slave_gamma.product (name, price) VALUES('slaveGamma', '1'); 69 | 70 | ``` 71 | 72 | ## 配置数据源 73 | 74 | - application.properties 75 | 76 | ```properties 77 | spring.datasource.type=com.zaxxer.hikari.HikariDataSource 78 | # Master datasource config 79 | spring.datasource.hikari.master.name=master 80 | spring.datasource.hikari.master.driver-class-name=com.mysql.jdbc.Driver 81 | spring.datasource.hikari.master.jdbc-url=jdbc:mysql://localhost/product_master?useSSL=false 82 | spring.datasource.hikari.master.port=3306 83 | spring.datasource.hikari.master.username=root 84 | spring.datasource.hikari.master.password=123456 85 | 86 | # SlaveAlpha datasource config 87 | spring.datasource.hikari.slave-alpha.name=SlaveAlpha 88 | spring.datasource.hikari.slave-alpha.driver-class-name=com.mysql.jdbc.Driver 89 | spring.datasource.hikari.slave-alpha.jdbc-url=jdbc:mysql://localhost/product_slave_alpha?useSSL=false 90 | spring.datasource.hikari.slave-alpha.port=3306 91 | spring.datasource.hikari.slave-alpha.username=root 92 | spring.datasource.hikari.slave-alpha.password=123456 93 | 94 | # SlaveBeta datasource config 95 | spring.datasource.hikari.slave-beta.name=SlaveBeta 96 | spring.datasource.hikari.slave-beta.driver-class-name=com.mysql.jdbc.Driver 97 | spring.datasource.hikari.slave-beta.jdbc-url=jdbc:mysql://localhost/product_slave_beta?useSSL=false 98 | spring.datasource.hikari.slave-beta.port=3306 99 | spring.datasource.hikari.slave-beta.username=root 100 | spring.datasource.hikari.slave-beta.password=123456 101 | 102 | # SlaveGamma datasource config 103 | spring.datasource.hikari.slave-gamma.name=SlaveGamma 104 | spring.datasource.hikari.slave-gamma.driver-class-name=com.mysql.jdbc.Driver 105 | spring.datasource.hikari.slave-gamma.jdbc-url=jdbc:mysql://localhost/product_slave_gamma?useSSL=false 106 | spring.datasource.hikari.slave-gamma.port=3306 107 | spring.datasource.hikari.slave-gamma.username=root 108 | spring.datasource.hikari.slave-gamma.password=123456 109 | 110 | spring.aop.proxy-target-class=true 111 | server.port=9999 112 | ``` 113 | 114 | ## 配置数据源 115 | 116 | - DataSourceKey.java 117 | ```java 118 | package cn.com.hellowood.dynamicdatasource.common; 119 | 120 | public enum DataSourceKey { 121 | master, 122 | slaveAlpha, 123 | slaveBeta, 124 | slaveGamma 125 | } 126 | 127 | ``` 128 | 129 | - DataSourceRoutingDataSource.java 130 | 131 | > 该类继承自 `AbstractRoutingDataSource` 类,在访问数据库时会调用该类的 `determineCurrentLookupKey()` 方法获取数据库实例的 key 132 | 133 | ```java 134 | package cn.com.hellowood.dynamicdatasource.configuration; 135 | 136 | import org.slf4j.Logger; 137 | import org.slf4j.LoggerFactory; 138 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 139 | 140 | public class DynamicRoutingDataSource extends AbstractRoutingDataSource { 141 | 142 | private final Logger logger = LoggerFactory.getLogger(getClass()); 143 | 144 | @Override 145 | protected Object determineCurrentLookupKey() { 146 | logger.info("Current DataSource is [{}]", DynamicDataSourceContextHolder.getDataSourceKey()); 147 | return DynamicDataSourceContextHolder.getDataSourceKey(); 148 | } 149 | } 150 | 151 | ``` 152 | 153 | - DataSourceConfigurer.java 154 | 155 | > 数据源配置类,在该类中生成多个数据源实例并将其注入到 `ApplicationContext` 中 156 | 157 | ```java 158 | package cn.com.hellowood.dynamicdatasource.configuration; 159 | 160 | import org.mybatis.spring.SqlSessionFactoryBean; 161 | import org.springframework.boot.jdbc.DataSourceBuilder; 162 | import org.springframework.boot.context.properties.ConfigurationProperties; 163 | import org.springframework.context.annotation.Bean; 164 | import org.springframework.context.annotation.Configuration; 165 | import org.springframework.context.annotation.Primary; 166 | 167 | import javax.sql.DataSource; 168 | import java.util.HashMap; 169 | import java.util.Map; 170 | 171 | @Configuration 172 | public class DataSourceConfigurer { 173 | 174 | /** 175 | * master DataSource 176 | * @Primary 注解用于标识默认使用的 DataSource Bean,因为有5个 DataSource Bean,该注解可用于 master 177 | * 或 slave DataSource Bean, 但不能用于 dynamicDataSource Bean, 否则会产生循环调用 178 | * 179 | * @ConfigurationProperties 注解用于从 application.properties 文件中读取配置,为 Bean 设置属性 180 | * @return data source 181 | */ 182 | @Bean("master") 183 | @Primary 184 | @ConfigurationProperties(prefix = "spring.datasource.hikari.master") 185 | public DataSource master() { 186 | return DataSourceBuilder.create().build(); 187 | } 188 | 189 | /** 190 | * Slave alpha data source. 191 | * 192 | * @return the data source 193 | */ 194 | @Bean("slaveAlpha") 195 | @ConfigurationProperties(prefix = "spring.datasource.hikari.slave-alpha") 196 | public DataSource slaveAlpha() { 197 | return DataSourceBuilder.create().build(); 198 | } 199 | 200 | /** 201 | * Slave beta data source. 202 | * 203 | * @return the data source 204 | */ 205 | @Bean("slaveBeta") 206 | @ConfigurationProperties(prefix = "spring.datasource.hikari.slave-beta") 207 | public DataSource slaveBeta() { 208 | return DataSourceBuilder.create().build(); 209 | } 210 | 211 | /** 212 | * Slave gamma data source. 213 | * 214 | * @return the data source 215 | */ 216 | @Bean("slaveGamma") 217 | @ConfigurationProperties(prefix = "spring.datasource.druid.slave-gamma") 218 | public DataSource slaveGamma() { 219 | return DataSourceBuilder.create().build(); 220 | } 221 | 222 | /** 223 | * Dynamic data source. 224 | * 225 | * @return the data source 226 | */ 227 | @Bean("dynamicDataSource") 228 | public DataSource dynamicDataSource() { 229 | DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); 230 | Map dataSourceMap = new HashMap<>(4); 231 | dataSourceMap.put(DataSourceKey.master.name(), master()); 232 | dataSourceMap.put(DataSourceKey.slaveAlpha.name(), slaveAlpha()); 233 | dataSourceMap.put(DataSourceKey.slaveBeta.name(), slaveBeta()); 234 | dataSourceMap.put(DataSourceKey.slaveGamma.name(), slaveGamma()); 235 | 236 | // 将 master 数据源作为默认指定的数据源 237 | dynamicRoutingDataSource.setDefaultTargetDataSource(master()); 238 | // 将 master 和 slave 数据源作为指定的数据源 239 | dynamicRoutingDataSource.setTargetDataSources(dataSourceMap); 240 | 241 | // 将数据源的 key 放到数据源上下文的 key 集合中,用于切换时判断数据源是否有效 242 | DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet()); 243 | 244 | // 将 Slave 数据源的 key 放在集合中,用于轮循 245 | DynamicDataSourceContextHolder.slaveDataSourceKeys.addAll(dataSourceMap.keySet()); 246 | DynamicDataSourceContextHolder.slaveDataSourceKeys.remove(DataSourceKey.master.name()); 247 | return dynamicRoutingDataSource; 248 | } 249 | 250 | /** 251 | * 配置 SqlSessionFactoryBean 252 | * @ConfigurationProperties 在这里是为了将 MyBatis 的 mapper 位置和持久层接口的别名设置到 253 | * Bean 的属性中,如果没有使用 *.xml 则可以不用该配置,否则将会产生 invalid bond statement 异常 254 | * 255 | * @return the sql session factory bean 256 | */ 257 | @Bean 258 | @ConfigurationProperties(prefix = "mybatis") 259 | public SqlSessionFactoryBean sqlSessionFactoryBean() { 260 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 261 | // 配置 MyBatis 262 | sqlSessionFactoryBean.setTypeAliasesPackage("cn.com.hellowood.dynamicdatasource.mapper"); 263 | sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mappers/**Mapper.xml")); 264 | 265 | // 配置数据源,此处配置为关键配置,如果没有将 dynamicDataSource 作为数据源则不能实现切换 266 | sqlSessionFactoryBean.setDataSource(dynamicDataSource()); 267 | return sqlSessionFactoryBean; 268 | } 269 | 270 | /** 271 | * 注入 DataSourceTransactionManager 用于事务管理 272 | */ 273 | @Bean 274 | public PlatformTransactionManager transactionManager() { 275 | return new DataSourceTransactionManager(dynamicDataSource()); 276 | } 277 | 278 | } 279 | 280 | ``` 281 | 282 | - DynamicDataSourceContextHolder.java 283 | 284 | > 该类为数据源上下文配置,用于切换数据源 285 | 286 | ```java 287 | package cn.com.hellowood.dynamicdatasource.configuration; 288 | 289 | 290 | import cn.com.hellowood.dynamicdatasource.common.DataSourceKey; 291 | import org.slf4j.Logger; 292 | import org.slf4j.LoggerFactory; 293 | 294 | import java.util.ArrayList; 295 | import java.util.List; 296 | 297 | public class DynamicDataSourceContextHolder { 298 | 299 | private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); 300 | 301 | /** 302 | * 用于轮循的计数器 303 | */ 304 | private static int counter = 0; 305 | 306 | /** 307 | * Maintain variable for every thread, to avoid effect other thread 308 | */ 309 | private static final ThreadLocal CONTEXT_HOLDER = ThreadLocal.withInitial(DataSourceKey.master); 310 | 311 | 312 | /** 313 | * All DataSource List 314 | */ 315 | public static List dataSourceKeys = new ArrayList<>(); 316 | 317 | /** 318 | * The constant slaveDataSourceKeys. 319 | */ 320 | public static List slaveDataSourceKeys = new ArrayList<>(); 321 | 322 | /** 323 | * To switch DataSource 324 | * 325 | * @param key the key 326 | */ 327 | public static void setDataSourceKey(String key) { 328 | CONTEXT_HOLDER.set(key); 329 | } 330 | 331 | /** 332 | * Use master data source. 333 | */ 334 | public static void useMasterDataSource() { 335 | CONTEXT_HOLDER.set(DataSourceKey.master); 336 | } 337 | 338 | /** 339 | * 当使用只读数据源时通过轮循方式选择要使用的数据源 340 | */ 341 | public static void useSlaveDataSource() { 342 | 343 | try { 344 | int datasourceKeyIndex = counter % slaveDataSourceKeys.size(); 345 | CONTEXT_HOLDER.set(String.valueOf(slaveDataSourceKeys.get(datasourceKeyIndex))); 346 | counter++; 347 | } catch (Exception e) { 348 | logger.error("Switch slave datasource failed, error message is {}", e.getMessage()); 349 | useMasterDataSource(); 350 | e.printStackTrace(); 351 | } 352 | } 353 | 354 | /** 355 | * Get current DataSource 356 | * 357 | * @return data source key 358 | */ 359 | public static String getDataSourceKey() { 360 | return CONTEXT_HOLDER.get(); 361 | } 362 | 363 | /** 364 | * To set DataSource as default 365 | */ 366 | public static void clearDataSourceKey() { 367 | CONTEXT_HOLDER.remove(); 368 | } 369 | 370 | /** 371 | * Check if give DataSource is in current DataSource list 372 | * 373 | * @param key the key 374 | * @return boolean boolean 375 | */ 376 | public static boolean containDataSourceKey(String key) { 377 | return dataSourceKeys.contains(key); 378 | } 379 | } 380 | 381 | 382 | ``` 383 | 384 | - DynamicDataSourceAspect.java 385 | 386 | > 动态数据源切换的切面,切 DAO 层,通过 DAO 层方法名判断使用哪个数据源,实现数据源切换 387 | > 关于切面的 Order 可以不设,因为 `@Transactional` 是最低的,取决于其他切面的设置,并且在 `org.springframework.core.annotation.AnnotationAwareOrderComparator` 会重新排序 388 | 389 | ```java 390 | package cn.com.hellowood.dynamicdatasource.configuration; 391 | 392 | import org.aspectj.lang.JoinPoint; 393 | import org.aspectj.lang.annotation.After; 394 | import org.aspectj.lang.annotation.Aspect; 395 | import org.aspectj.lang.annotation.Before; 396 | import org.aspectj.lang.annotation.Pointcut; 397 | import org.slf4j.Logger; 398 | import org.slf4j.LoggerFactory; 399 | import org.springframework.stereotype.Component; 400 | 401 | @Aspect 402 | @Component 403 | public class DynamicDataSourceAspect { 404 | private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class); 405 | 406 | private final String[] QUERY_PREFIX = {"get"}; 407 | 408 | @Pointcut("execution( * cn.com.hellowood.dynamicdatasource.mapper.*.*(..))") 409 | public void daoAspect() { 410 | } 411 | 412 | @Before("daoAspect()") 413 | public void switchDataSource(JoinPoint point) { 414 | Boolean isQueryMethod = isQueryMethod(point.getSignature().getName()); 415 | if (isQueryMethod) { 416 | DynamicDataSourceContextHolder.useSlaveDataSource(); 417 | logger.info("Switch DataSource to [{}] in Method [{}]", 418 | DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature()); 419 | } 420 | } 421 | 422 | @After("daoAspect()") 423 | public void restoreDataSource(JoinPoint point) { 424 | DynamicDataSourceContextHolder.clearDataSourceKey(); 425 | logger.info("Restore DataSource to [{}] in Method [{}]", 426 | DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature()); 427 | } 428 | 429 | private Boolean isQueryMethod(String methodName) { 430 | for (String prefix : QUERY_PREFIX) { 431 | if (methodName.startsWith(prefix)) { 432 | return true; 433 | } 434 | } 435 | return false; 436 | } 437 | 438 | } 439 | 440 | ``` 441 | 442 | 443 | ## 配置 Product REST API 接口 444 | 445 | - ProductController.java 446 | 447 | ```java 448 | package cn.com.hellowood.dynamicdatasource.controller; 449 | 450 | import cn.com.hellowood.dynamicdatasource.common.CommonResponse; 451 | import cn.com.hellowood.dynamicdatasource.common.ResponseUtil; 452 | import cn.com.hellowood.dynamicdatasource.model.Product; 453 | import cn.com.hellowood.dynamicdatasource.service.ProductService; 454 | import cn.com.hellowood.dynamicdatasource.error.ServiceException; 455 | import org.springframework.beans.factory.annotation.Autowired; 456 | import org.springframework.web.bind.annotation.*; 457 | 458 | @RestController 459 | @RequestMapping("/product") 460 | public class ProductController { 461 | 462 | @Autowired 463 | private ProductService productService; 464 | 465 | @GetMapping("/{id}") 466 | public CommonResponse getProduct(@PathVariable("id") Long productId) throws ServiceException { 467 | return ResponseUtil.generateResponse(productService.select(productId)); 468 | } 469 | 470 | @GetMapping 471 | public CommonResponse getAllProduct() { 472 | return ResponseUtil.generateResponse(productService.getAllProduct()); 473 | } 474 | 475 | @PutMapping("/{id}") 476 | public CommonResponse updateProduct(@PathVariable("id") Long productId, @RequestBody Product newProduct) throws ServiceException { 477 | return ResponseUtil.generateResponse(productService.update(productId, newProduct)); 478 | } 479 | 480 | @DeleteMapping("/{id}") 481 | public CommonResponse deleteProduct(@PathVariable("id") long productId) throws ServiceException { 482 | return ResponseUtil.generateResponse(productService.delete(productId)); 483 | } 484 | 485 | @PostMapping 486 | public CommonResponse addProduct(@RequestBody Product newProduct) throws ServiceException { 487 | return ResponseUtil.generateResponse(productService.add(newProduct)); 488 | } 489 | } 490 | 491 | 492 | ``` 493 | 494 | - ProductService.java 495 | ```java 496 | package cn.com.hellowood.dynamicdatasource.service; 497 | 498 | import cn.com.hellowood.dynamicdatasource.mapper.ProductDao; 499 | import cn.com.hellowood.dynamicdatasource.model.Product; 500 | import cn.com.hellowood.dynamicdatasource.error.ServiceException; 501 | import org.springframework.beans.factory.annotation.Autowired; 502 | import org.springframework.dao.DataAccessException; 503 | import org.springframework.stereotype.Service; 504 | import org.springframework.transaction.annotation.Transactional; 505 | 506 | import java.util.List; 507 | 508 | @Service 509 | public class ProductService { 510 | 511 | @Autowired 512 | private ProductDao productDao; 513 | 514 | public Product select(long productId) throws ServiceException { 515 | Product product = productDao.select(productId); 516 | if (product == null) { 517 | throw new ServiceException("Product:" + productId + " not found"); 518 | } 519 | return product; 520 | } 521 | 522 | @Transactional(rollbackFor = DataAccessException.class) 523 | public Product update(long productId, Product newProduct) throws ServiceException { 524 | 525 | if (productDao.update(newProduct) <= 0) { 526 | throw new ServiceException("Update product:" + productId + "failed"); 527 | } 528 | return newProduct; 529 | } 530 | 531 | @Transactional(rollbackFor = DataAccessException.class) 532 | public boolean add(Product newProduct) throws ServiceException { 533 | Integer num = productDao.insert(newProduct); 534 | if (num <= 0) { 535 | throw new ServiceException("Add product failed"); 536 | } 537 | return true; 538 | } 539 | 540 | @Transactional(rollbackFor = DataAccessException.class) 541 | public boolean delete(long productId) throws ServiceException { 542 | Integer num = productDao.delete(productId); 543 | if (num <= 0) { 544 | throw new ServiceException("Delete product:" + productId + "failed"); 545 | } 546 | return true; 547 | } 548 | 549 | public List getAllProduct() { 550 | return productDao.getAllProduct(); 551 | } 552 | } 553 | 554 | ``` 555 | 556 | - ProductDao.java 557 | 558 | ```java 559 | package cn.com.hellowood.dynamicdatasource.mapper; 560 | 561 | import cn.com.hellowood.dynamicdatasource.model.Product; 562 | import org.apache.ibatis.annotations.Mapper; 563 | import org.apache.ibatis.annotations.Param; 564 | 565 | import java.util.List; 566 | 567 | @Mapper 568 | public interface ProductDao { 569 | Product select(@Param("id") long id); 570 | 571 | Integer update(Product product); 572 | 573 | Integer insert(Product product); 574 | 575 | Integer delete(long productId); 576 | 577 | List getAllProduct(); 578 | } 579 | 580 | ``` 581 | 582 | - ProductMapper.xml 583 | 584 | > 启动项目,此时访问 `/product/1` 会返回 `product_master` 数据库中 `product` 表中的所有数据,多次访问 `/product` 会分别返回 `product_slave_alpha`、`product_slave_beta`、`product_slave_gamma` 数据库中 `product` 表中的数据,同时也可以在看到切换数据源的 log,说明动态切换数据源是有效的 585 | 586 | --------------- 587 | 588 | ## 注意 589 | 590 | > 在该应用中因为使用了 DAO 层的切面切换数据源,所以 `@Transactional` 注解不能加在类上,只能用于方法;有 `@Trasactional`注解的方法无法切换数据源 591 | 592 | 593 | ## Stargazers over time 594 | 595 | [![Stargazers over time](https://starchart.cc/helloworlde/SpringBoot-DynamicDataSource.svg)](https://starchart.cc/helloworlde/SpringBoot-DynamicDataSource) 596 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext { 3 | springBootVersion = '2.0.1.RELEASE' 4 | } 5 | repositories { 6 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 11 | } 12 | } 13 | 14 | apply plugin: 'java' 15 | apply plugin: 'eclipse' 16 | apply plugin: 'org.springframework.boot' 17 | apply plugin: 'io.spring.dependency-management' 18 | 19 | group = 'cn.com.hellowood' 20 | version = '0.0.1-SNAPSHOT' 21 | sourceCompatibility = 1.8 22 | 23 | repositories { 24 | maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } 25 | mavenCentral() 26 | } 27 | 28 | 29 | dependencies { 30 | compile('org.springframework.boot:spring-boot-starter-parent:2.0.1.RELEASE') 31 | compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2') 32 | compile('org.springframework.boot:spring-boot-starter-web') 33 | compile('org.springframework.boot:spring-boot-starter-aop') 34 | compile('com.alibaba:druid-spring-boot-starter:1.1.6') 35 | compile 'com.alibaba:fastjson:1.2.55' 36 | runtime('mysql:mysql-connector-java') 37 | testCompile('org.springframework.boot:spring-boot-starter-test') 38 | } 39 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/helloworlde/SpringBoot-DynamicDataSource/8e7e6fda9a909a9ab217b9331748af5218db491e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri May 11 12:58:07 CST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://rdc-public-software.oss-cn-hangzhou.aliyuncs.com/gradle-4.1-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/DynamicDataSourceApplication.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DynamicDataSourceApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(DynamicDataSourceApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/annotation/ApiResponseBody.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.annotation; 2 | 3 | import com.alibaba.fastjson.serializer.SerializerFeature; 4 | 5 | import java.lang.annotation.*; 6 | 7 | /** 8 | * 会在拦截器那里判断是否有这个注解,如果存在把结果包装成 {code:'',data:''} 的形式 9 | * 10 | * @author LDZ 11 | * @date 2020-03-02 16:36 12 | */ 13 | @Target({ElementType.TYPE, ElementType.METHOD}) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Documented 16 | public @interface ApiResponseBody { 17 | /** 18 | * 序列化可选 fastjson 19 | * 20 | * @return 21 | * @see SerializerFeature 22 | */ 23 | SerializerFeature[] serializerFeature() default {}; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/config/BaseWebMvcConfig.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.config; 2 | 3 | 4 | import cn.com.hellowood.dynamicdatasource.apiutil.interceptor.ApiResponseBodyReturnValueHandler; 5 | import cn.com.hellowood.dynamicdatasource.configuration.CustomHandlerExceptionResolver; 6 | import com.alibaba.fastjson.support.config.FastJsonConfig; 7 | import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 8 | import org.springframework.format.FormatterRegistry; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.http.converter.HttpMessageConverter; 11 | import org.springframework.validation.MessageCodesResolver; 12 | import org.springframework.validation.Validator; 13 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 14 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 15 | import org.springframework.web.servlet.HandlerExceptionResolver; 16 | import org.springframework.web.servlet.config.annotation.*; 17 | 18 | import java.util.Collections; 19 | import java.util.List; 20 | 21 | 22 | /** 23 | * spring boot web 通用配置 24 | * 25 | * @author LDZ 26 | * @date 2020-03-02 17:12 27 | */ 28 | public abstract class BaseWebMvcConfig implements WebMvcConfigurer { 29 | 30 | @Override 31 | public void addReturnValueHandlers(List returnValueHandlers) { 32 | returnValueHandlers.add(new ApiResponseBodyReturnValueHandler()); 33 | } 34 | 35 | @Override 36 | public void addInterceptors(InterceptorRegistry registry) { 37 | } 38 | 39 | @Override 40 | public void configureMessageConverters(List> converters) { 41 | FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); 42 | FastJsonConfig fastJsonConfig = new FastJsonConfig(); 43 | 44 | fastJsonConfig.setSerializerFeatures( 45 | // SerializerFeature.PrettyFormat 46 | ); 47 | 48 | fastConverter.setFastJsonConfig(fastJsonConfig); 49 | fastConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); 50 | converters.add(0, fastConverter); 51 | 52 | } 53 | 54 | @Override 55 | public void configurePathMatch(PathMatchConfigurer configurer) { 56 | 57 | } 58 | 59 | @Override 60 | public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 61 | 62 | } 63 | 64 | @Override 65 | public void configureAsyncSupport(AsyncSupportConfigurer configurer) { 66 | 67 | } 68 | 69 | @Override 70 | public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 71 | 72 | } 73 | 74 | @Override 75 | public void addFormatters(FormatterRegistry registry) { 76 | 77 | } 78 | 79 | @Override 80 | public void addResourceHandlers(ResourceHandlerRegistry registry) { 81 | 82 | } 83 | 84 | @Override 85 | public void addCorsMappings(CorsRegistry registry) { 86 | 87 | } 88 | 89 | @Override 90 | public void addViewControllers(ViewControllerRegistry registry) { 91 | 92 | } 93 | 94 | @Override 95 | public void configureViewResolvers(ViewResolverRegistry registry) { 96 | 97 | } 98 | 99 | @Override 100 | public void addArgumentResolvers(List argumentResolvers) { 101 | 102 | } 103 | 104 | @Override 105 | public void extendMessageConverters(List> converters) { 106 | 107 | } 108 | 109 | @Override 110 | public void configureHandlerExceptionResolvers(List exceptionResolvers) { 111 | exceptionResolvers.add(new CustomHandlerExceptionResolver()); 112 | } 113 | 114 | @Override 115 | public void extendHandlerExceptionResolvers(List exceptionResolvers) { 116 | 117 | } 118 | 119 | @Override 120 | public Validator getValidator() { 121 | return null; 122 | } 123 | 124 | @Override 125 | public MessageCodesResolver getMessageCodesResolver() { 126 | return null; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/exception/BaseExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.exception; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.model.BaseResponse; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.validation.BindException; 7 | import org.springframework.web.bind.MissingServletRequestParameterException; 8 | import org.springframework.web.bind.annotation.ControllerAdvice; 9 | import org.springframework.web.bind.annotation.ExceptionHandler; 10 | import org.springframework.web.bind.annotation.ResponseBody; 11 | 12 | import javax.servlet.http.HttpServletRequest; 13 | import javax.servlet.http.HttpServletResponse; 14 | import java.util.Optional; 15 | import java.util.stream.Collectors; 16 | 17 | import static cn.com.hellowood.dynamicdatasource.apiutil.exception.enums.CustomExceptionEnum.PARAM_ERROR; 18 | 19 | /** 20 | * 错误处理句柄 21 | * 22 | * @author LDZ 23 | * @date 2020-03-02 17:19 24 | */ 25 | 26 | @ControllerAdvice 27 | public class BaseExceptionHandler { 28 | 29 | private static final Logger log = LoggerFactory.getLogger(BaseExceptionHandler.class); 30 | 31 | /** 32 | * @param request 请求 33 | * @param response 返回 34 | * @param handler 句柄 35 | * @param ex 错误 36 | * @return 统一封装返回值 37 | */ 38 | @ResponseBody 39 | @ExceptionHandler(MissingServletRequestParameterException.class) 40 | public BaseResponse argumentMissingError(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 41 | return PARAM_ERROR.handlerBaseResponse("参数错误"); 42 | } 43 | 44 | @ResponseBody 45 | @ExceptionHandler(BindException.class) 46 | public BaseResponse bindError(HttpServletRequest request, HttpServletResponse response, Object handler, BindException ex) { 47 | String errMessage = ex.getFieldErrors().stream().map(fieldError -> fieldError.getField() + ":" + fieldError.getDefaultMessage()).collect(Collectors.joining(",")); 48 | log.warn("server param error ", ex); 49 | return PARAM_ERROR.handlerBaseResponse(errMessage); 50 | 51 | } 52 | 53 | 54 | /** 55 | * 抓取所有的错误 56 | * 57 | * @param request 58 | * @param response 59 | * @param handler 60 | * @param ex 61 | * @return 62 | */ 63 | @ResponseBody 64 | @ExceptionHandler(Exception.class) 65 | public BaseResponse defaultErrorHandle(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 66 | log.error("server error ", ex); 67 | return PARAM_ERROR.handlerBaseResponse("服务器繁忙"); 68 | } 69 | 70 | 71 | @ResponseBody 72 | @ExceptionHandler(CustomServiceException.class) 73 | public BaseResponse customExceptionHandle(HttpServletRequest request, HttpServletResponse response, Object handler, CustomServiceException customServiceException) { 74 | 75 | log.debug("business err {} ", customServiceException.getErrorDescription()); 76 | return customServiceException.getCustomExceptionEnum().handlerBaseResponse( 77 | Optional.ofNullable(customServiceException.getErrorDescription()).orElse("服务器繁忙"), 78 | Optional.ofNullable(customServiceException.getData()).orElse(null)); 79 | 80 | 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/exception/CustomServiceException.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.exception; 2 | 3 | /** 4 | * @author XiaoLei 5 | * @date 2018/4/17 15:19 6 | * @description 7 | */ 8 | 9 | import cn.com.hellowood.dynamicdatasource.apiutil.exception.enums.CustomExceptionEnum; 10 | 11 | /** 12 | * 自定义异常 13 | * 14 | * @author LDZ 15 | * @date 2020-03-02 17:22 16 | */ 17 | public class CustomServiceException extends RuntimeException { 18 | 19 | /** 20 | * 自定义错误 21 | */ 22 | private CustomExceptionEnum customExceptionEnum; 23 | 24 | /** 25 | * 错误的描述 26 | */ 27 | private String errorDescription; 28 | 29 | /** 30 | * 需要返回的数据 31 | */ 32 | private Object data; 33 | 34 | 35 | public CustomServiceException(CustomExceptionEnum customExceptionEnum, String desc) { 36 | super(desc); 37 | this.customExceptionEnum = customExceptionEnum; 38 | this.errorDescription = desc; 39 | } 40 | 41 | public CustomServiceException(CustomExceptionEnum customExceptionEnum, String desc, Object data) { 42 | super(desc); 43 | this.customExceptionEnum = customExceptionEnum; 44 | this.errorDescription = desc; 45 | this.data = data; 46 | } 47 | 48 | public CustomExceptionEnum getCustomExceptionEnum() { 49 | return customExceptionEnum; 50 | } 51 | 52 | public void setCustomExceptionEnum(CustomExceptionEnum customExceptionEnum) { 53 | this.customExceptionEnum = customExceptionEnum; 54 | } 55 | 56 | public String getErrorDescription() { 57 | return errorDescription; 58 | } 59 | 60 | public void setErrorDescription(String errorDescription) { 61 | this.errorDescription = errorDescription; 62 | } 63 | 64 | public Object getData() { 65 | return data; 66 | } 67 | 68 | public void setData(Object data) { 69 | this.data = data; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/exception/enums/CustomExceptionEnum.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.exception.enums; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.exception.CustomServiceException; 4 | import cn.com.hellowood.dynamicdatasource.apiutil.model.BaseResponse; 5 | import jdk.nashorn.internal.objects.annotations.Getter; 6 | 7 | import java.util.function.BiFunction; 8 | 9 | /** 10 | * @author LDZ 11 | * @date 2020-03-02 17:23 12 | */ 13 | public enum CustomExceptionEnum { 14 | 15 | 16 | /** 17 | * 业务的参数错误 18 | */ 19 | PARAM_ERROR(105) { 20 | // override 21 | 22 | }; 23 | 24 | 25 | int code; 26 | 27 | public RuntimeException handlerException(String s, Object d) { 28 | return new CustomServiceException(this, s, d); 29 | } 30 | 31 | public RuntimeException handlerException(String s) { 32 | return new CustomServiceException(this, s); 33 | } 34 | 35 | public BaseResponse handlerBaseResponse(String s, Object d) { 36 | return new BaseResponse(this, s, d); 37 | } 38 | 39 | public BaseResponse handlerBaseResponse(String s) { 40 | return new BaseResponse(this, s); 41 | } 42 | 43 | public int getCode() { 44 | return code; 45 | } 46 | 47 | CustomExceptionEnum(int code) { 48 | this.code = code; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/interceptor/ApiResponseBodyReturnValueHandler.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.interceptor; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.annotation.ApiResponseBody; 4 | import cn.com.hellowood.dynamicdatasource.apiutil.model.BaseResponse; 5 | import com.alibaba.fastjson.JSON; 6 | import com.alibaba.fastjson.serializer.SerializerFeature; 7 | import org.springframework.core.MethodParameter; 8 | import org.springframework.web.context.request.NativeWebRequest; 9 | import org.springframework.web.method.support.AsyncHandlerMethodReturnValueHandler; 10 | import org.springframework.web.method.support.HandlerMethodReturnValueHandler; 11 | import org.springframework.web.method.support.ModelAndViewContainer; 12 | 13 | import javax.servlet.http.HttpServletResponse; 14 | 15 | /** 16 | * api 层返回值处理句柄 17 | * 18 | * @author LDZ 19 | * @date 2020-03-02 16:43 20 | */ 21 | public class ApiResponseBodyReturnValueHandler implements HandlerMethodReturnValueHandler, AsyncHandlerMethodReturnValueHandler { 22 | /** 23 | * 处理的返回类型 24 | * 25 | * @param returnType 返回类型 26 | * @return true 处理 false 不处理 27 | */ 28 | @Override 29 | public boolean supportsReturnType(MethodParameter returnType) { 30 | // 如果已经是基础的返回值 31 | return returnType.getParameterType() != ApiResponseBody.class 32 | && (returnType.getAnnotatedElement().getAnnotation(ApiResponseBody.class) != null); 33 | } 34 | 35 | @Override 36 | public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { 37 | mavContainer.setRequestHandled(true); 38 | HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); 39 | assert response != null; 40 | response.setContentType("application/json;charset=utf-8"); 41 | BaseResponse baseResponse = new BaseResponse(); 42 | baseResponse.setCode(100); 43 | baseResponse.setMessage("成功"); 44 | baseResponse.setData(returnValue); 45 | 46 | ApiResponseBody apiResponseBody = returnType.getAnnotatedElement().getAnnotation(ApiResponseBody.class); 47 | 48 | SerializerFeature[] defaultSerializerFeature = { 49 | SerializerFeature.DisableCircularReferenceDetect 50 | }; 51 | 52 | if (apiResponseBody != null && apiResponseBody.serializerFeature().length != 0) { 53 | defaultSerializerFeature = apiResponseBody.serializerFeature(); 54 | } 55 | response.getWriter().write(JSON.toJSONString(baseResponse, defaultSerializerFeature)); 56 | 57 | } 58 | 59 | @Override 60 | public boolean isAsyncReturnValue(Object returnValue, MethodParameter returnType) { 61 | return supportsReturnType(returnType); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/apiutil/model/BaseResponse.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.apiutil.model; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.exception.enums.CustomExceptionEnum; 4 | 5 | import java.io.Serializable; 6 | 7 | /** 8 | * 统一返回标志 9 | * 10 | * @author LDZ 11 | * @date 2020-03-02 16:48 12 | */ 13 | public class BaseResponse implements Serializable { 14 | 15 | private static final long serialVersionUID = -6818493817970279447L; 16 | /** 17 | * 返回code码 18 | */ 19 | private int code; 20 | 21 | /** 22 | * 返回信息 23 | */ 24 | private String message; 25 | 26 | /** 27 | * 返回数据 28 | */ 29 | private Object data; 30 | 31 | public int getCode() { 32 | return code; 33 | } 34 | 35 | public void setCode(int code) { 36 | this.code = code; 37 | } 38 | 39 | public String getMessage() { 40 | return message; 41 | } 42 | 43 | public void setMessage(String message) { 44 | this.message = message; 45 | } 46 | 47 | public Object getData() { 48 | return data; 49 | } 50 | 51 | public void setData(Object data) { 52 | this.data = data; 53 | } 54 | 55 | 56 | public BaseResponse() { 57 | } 58 | 59 | public BaseResponse(int code, String message, Object data) { 60 | this.code = code; 61 | this.message = message; 62 | this.data = data; 63 | } 64 | 65 | public BaseResponse(int code, String message) { 66 | this.code = code; 67 | this.message = message; 68 | } 69 | 70 | public BaseResponse(CustomExceptionEnum customExceptionEnum, String message, Object data) { 71 | this.code = customExceptionEnum.getCode(); 72 | this.message = message; 73 | this.data = data; 74 | } 75 | 76 | public BaseResponse(CustomExceptionEnum customExceptionEnum, String message) { 77 | this.code = customExceptionEnum.getCode(); 78 | this.message = message; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/common/CommonConstant.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.common; 2 | 3 | /** 4 | * Common constant 5 | * 6 | * @author HelloWood 7 | * @date 2017-07-11 15:46 8 | * @Email hellowoodes@gmail.com 9 | */ 10 | public class CommonConstant { 11 | 12 | /** 13 | * Request result message 14 | */ 15 | public static final String DEFAULT_SUCCESS_MESSAGE = "success"; 16 | public static final String DEFAULT_FAIL_MESSAGE = "fail"; 17 | public static final String NO_RESULT_MESSAGE = "no result"; 18 | 19 | /** 20 | * Operation status 21 | */ 22 | public static final String SUCCESS = "SUCCESS"; 23 | public static final String ERROR = "ERROR"; 24 | 25 | /** 26 | * Error or exception message 27 | */ 28 | public static final String DB_ERROR_MESSAGE = "Database Error"; 29 | public static final String SERVER_ERROR_MESSAGE = "Server Error"; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/common/CommonResponse.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.common; 2 | 3 | 4 | import cn.com.hellowood.dynamicdatasource.utils.JSONUtil; 5 | 6 | /** 7 | * Response bean for format response 8 | * 9 | * @author HelloWood 10 | * @date 2017-07-11 15:33 11 | * @Email hellowoodes@gmail.com 12 | */ 13 | public class CommonResponse { 14 | 15 | private int code; 16 | private String message; 17 | private Object data; 18 | 19 | public int getCode() { 20 | return code; 21 | } 22 | 23 | public CommonResponse setCode(ResponseCode responseCode) { 24 | this.code = responseCode.code; 25 | return this; 26 | } 27 | 28 | public String getMessage() { 29 | return message; 30 | } 31 | 32 | public CommonResponse setMessage(String message) { 33 | this.message = message; 34 | return this; 35 | } 36 | 37 | public Object getData() { 38 | return data; 39 | } 40 | 41 | public CommonResponse setData(Object data) { 42 | this.data = data; 43 | return this; 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return JSONUtil.toJSONString(this); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/common/DataSourceKey.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.common; 2 | 3 | /** 4 | * The enum Data source key. 5 | * 6 | * @author HelloWood 7 | * @date 2017-08-15 14:26 8 | * @Email hellowoodes@gmail.com 9 | */ 10 | public enum DataSourceKey { 11 | /** 12 | * Master data source key. 13 | */ 14 | master, 15 | /** 16 | * Slave alpha data source key. 17 | */ 18 | slaveAlpha, 19 | /** 20 | * Slave beta data source key. 21 | */ 22 | slaveBeta, 23 | /** 24 | * Slave gamma data source key. 25 | */ 26 | slaveGamma 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/common/ResponseCode.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.common; 2 | 3 | /** 4 | * Response code 5 | * 6 | * @author HelloWood 7 | * @date 2017-07-11 15:41 8 | * @Email hellowoodes@gmail.com 9 | */ 10 | public enum ResponseCode { 11 | SUCCESS(200), 12 | FAIL(400), 13 | UNAUTHORIZED(401), 14 | NOT_FOUND(404), 15 | INTERNAL_SERVER_ERROR(500); 16 | 17 | public int code; 18 | 19 | ResponseCode(int code) { 20 | this.code = code; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/common/ResponseUtil.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.common; 2 | 3 | import cn.com.hellowood.dynamicdatasource.utils.JSONUtil; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import javax.servlet.http.HttpServletResponse; 8 | import java.io.IOException; 9 | 10 | /** 11 | * Generate response for request 12 | * 13 | * @author HelloWood 14 | * @date 2017-07-11 15:45 15 | * @Email hellowoodes@gmail.com 16 | */ 17 | public class ResponseUtil { 18 | 19 | private static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class); 20 | 21 | /** 22 | * Handler response information 23 | * 24 | * @param response 25 | * @param object 26 | * @return 27 | */ 28 | public static HttpServletResponse handlerResponse(HttpServletResponse response, Object object) { 29 | response.setCharacterEncoding("UTF-8"); 30 | response.setHeader("Content-type", "application/json;charset=UTF-8"); 31 | response.setStatus(200); 32 | try { 33 | response.getWriter().write(JSONUtil.toJSONString(object)); 34 | } catch (IOException e) { 35 | logger.error(e.getMessage()); 36 | } 37 | return response; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/CustomHandlerExceptionResolver.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | import cn.com.hellowood.dynamicdatasource.common.CommonConstant; 4 | import cn.com.hellowood.dynamicdatasource.common.CommonResponse; 5 | import cn.com.hellowood.dynamicdatasource.common.ResponseCode; 6 | import cn.com.hellowood.dynamicdatasource.common.ResponseUtil; 7 | import cn.com.hellowood.dynamicdatasource.error.ServiceException; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.dao.DataAccessException; 11 | import org.springframework.web.method.HandlerMethod; 12 | import org.springframework.web.servlet.HandlerExceptionResolver; 13 | import org.springframework.web.servlet.ModelAndView; 14 | import org.springframework.web.servlet.NoHandlerFoundException; 15 | 16 | import javax.servlet.http.HttpServletRequest; 17 | import javax.servlet.http.HttpServletResponse; 18 | 19 | /** 20 | * Custom exception handler 21 | * 22 | * @author HelloWood 23 | * @date 2017-07-11 21:03 24 | * @Email hellowoodes@gmail.com 25 | */ 26 | public class CustomHandlerExceptionResolver implements HandlerExceptionResolver { 27 | private final Logger logger = LoggerFactory.getLogger(CustomHandlerExceptionResolver.class); 28 | 29 | @Override 30 | public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 31 | 32 | CommonResponse commonResponse = new CommonResponse(); 33 | if (handler instanceof HandlerMethod) { 34 | HandlerMethod handlerMethod = (HandlerMethod) handler; 35 | //Service exception,handler exception from service 36 | if (ex instanceof ServiceException) { 37 | commonResponse.setCode(ResponseCode.SUCCESS).setMessage(ex.getMessage()); 38 | logger.warn(ex.getMessage()); 39 | } else { 40 | //DB exception 41 | if (ex instanceof DataAccessException) { 42 | commonResponse.setCode(ResponseCode.INTERNAL_SERVER_ERROR) 43 | .setMessage(CommonConstant.DB_ERROR_MESSAGE); 44 | } else { 45 | //Others exception 46 | commonResponse.setCode(ResponseCode.INTERNAL_SERVER_ERROR) 47 | .setMessage(CommonConstant.SERVER_ERROR_MESSAGE); 48 | } 49 | 50 | // error message detail 51 | String message = String.format("interface [%s] has exception,method is %s.%s, exception message is %s", 52 | request.getRequestURI(), 53 | handlerMethod.getBean().getClass().getName(), 54 | handlerMethod.getMethod().getName(), 55 | ex.getMessage()); 56 | 57 | logger.error(message, ex); 58 | } 59 | } else { 60 | if (ex instanceof NoHandlerFoundException) { 61 | commonResponse.setCode(ResponseCode.NOT_FOUND).setMessage("interface [" + request.getRequestURI() + "] not exist"); 62 | } else { 63 | commonResponse.setCode(ResponseCode.INTERNAL_SERVER_ERROR).setMessage(ex.getMessage()); 64 | logger.error(ex.getMessage(), ex); 65 | } 66 | } 67 | 68 | ResponseUtil.handlerResponse(response, commonResponse); 69 | return new ModelAndView(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/DataSourceConfigurer.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | import cn.com.hellowood.dynamicdatasource.common.DataSourceKey; 4 | import org.mybatis.spring.SqlSessionFactoryBean; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.boot.jdbc.DataSourceBuilder; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.Primary; 10 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 11 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 12 | import org.springframework.transaction.PlatformTransactionManager; 13 | 14 | import javax.sql.DataSource; 15 | import java.io.IOException; 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * Multiple DataSource Configurer 21 | * 22 | * @author HelloWood 23 | * @date 2017 -08-15 11:37 24 | * @Email hellowoodes @gmail.com 25 | */ 26 | @Configuration 27 | public class DataSourceConfigurer { 28 | 29 | /** 30 | * master DataSource 31 | * 32 | * @return data source 33 | */ 34 | @Bean("master") 35 | @Primary 36 | @ConfigurationProperties(prefix = "spring.datasource.hikari.master") 37 | public DataSource master() { 38 | return DataSourceBuilder.create().build(); 39 | } 40 | 41 | /** 42 | * Slave alpha data source. 43 | * 44 | * @return the data source 45 | */ 46 | @Bean("slaveAlpha") 47 | @ConfigurationProperties(prefix = "spring.datasource.hikari.slave-alpha") 48 | public DataSource slaveAlpha() { 49 | return DataSourceBuilder.create().build(); 50 | } 51 | 52 | /** 53 | * Slave beta data source. 54 | * 55 | * @return the data source 56 | */ 57 | @Bean("slaveBeta") 58 | @ConfigurationProperties(prefix = "spring.datasource.hikari.slave-beta") 59 | public DataSource slaveBeta() { 60 | return DataSourceBuilder.create().build(); 61 | } 62 | 63 | /** 64 | * Slave gamma data source. 65 | * 66 | * @return the data source 67 | */ 68 | @Bean("slaveGamma") 69 | @ConfigurationProperties(prefix = "spring.datasource.hikari.slave-gamma") 70 | public DataSource slaveGamma() { 71 | return DataSourceBuilder.create().build(); 72 | } 73 | 74 | /** 75 | * Dynamic data source. 76 | * 77 | * @return the data source 78 | */ 79 | @Bean("dynamicDataSource") 80 | public DataSource dynamicDataSource() { 81 | DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource(); 82 | Map dataSourceMap = new HashMap<>(4); 83 | dataSourceMap.put(DataSourceKey.master.name(), master()); 84 | dataSourceMap.put(DataSourceKey.slaveAlpha.name(), slaveAlpha()); 85 | dataSourceMap.put(DataSourceKey.slaveBeta.name(), slaveBeta()); 86 | dataSourceMap.put(DataSourceKey.slaveGamma.name(), slaveGamma()); 87 | 88 | // Set master datasource as default 89 | dynamicRoutingDataSource.setDefaultTargetDataSource(master()); 90 | // Set master and slave datasource as target datasource 91 | dynamicRoutingDataSource.setTargetDataSources(dataSourceMap); 92 | 93 | // To put datasource keys into DataSourceContextHolder to judge if the datasource is exist 94 | DynamicDataSourceContextHolder.dataSourceKeys.addAll(dataSourceMap.keySet()); 95 | 96 | // To put slave datasource keys into DataSourceContextHolder to load balance 97 | DynamicDataSourceContextHolder.slaveDataSourceKeys.addAll(dataSourceMap.keySet()); 98 | DynamicDataSourceContextHolder.slaveDataSourceKeys.remove(DataSourceKey.master.name()); 99 | return dynamicRoutingDataSource; 100 | } 101 | 102 | /** 103 | * Sql session factory bean. 104 | * Here to config datasource for SqlSessionFactory 105 | *

106 | * You need to add @{@code @ConfigurationProperties(prefix = "mybatis")}, if you are using *.xml file, 107 | * the {@code 'mybatis.type-aliases-package'} and {@code 'mybatis.mapper-locations'} should be set in 108 | * {@code 'application.properties'} file, or there will appear invalid bond statement exception 109 | * 110 | * @return the sql session factory bean 111 | */ 112 | @Bean 113 | @ConfigurationProperties(prefix = "mybatis") 114 | public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException { 115 | SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); 116 | // Here to config mybatis 117 | sqlSessionFactoryBean.setTypeAliasesPackage("cn.com.hellowood.dynamicdatasource.mapper"); 118 | sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mappers/**Mapper.xml")); 119 | // Here is very important, if don't config this, will can't switch datasource 120 | // put all datasource into SqlSessionFactoryBean, then will autoconfig SqlSessionFactory 121 | sqlSessionFactoryBean.setDataSource(dynamicDataSource()); 122 | return sqlSessionFactoryBean; 123 | } 124 | 125 | /** 126 | * Transaction manager platform transaction manager. 127 | * 128 | * @return the platform transaction manager 129 | */ 130 | @Bean 131 | public PlatformTransactionManager transactionManager() { 132 | return new DataSourceTransactionManager(dynamicDataSource()); 133 | } 134 | } 135 | 136 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/DynamicDataSourceAspect.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.annotation.After; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.annotation.Before; 7 | import org.aspectj.lang.annotation.Pointcut; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.stereotype.Component; 11 | 12 | /** 13 | * Multiple DataSource Aspect 14 | * 15 | * @author HelloWood 16 | * @date 2017-08-15 11:37 17 | * @email hellowoodes@gmail.com 18 | */ 19 | @Aspect 20 | @Component 21 | public class DynamicDataSourceAspect { 22 | private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class); 23 | 24 | private final String[] QUERY_PREFIX = {"get"}; 25 | 26 | /** 27 | * Dao aspect. 28 | */ 29 | @Pointcut("execution( * cn.com.hellowood.dynamicdatasource.mapper.*.*(..))") 30 | public void daoAspect() { 31 | } 32 | 33 | /** 34 | * Switch DataSource 35 | * 36 | * @param point the point 37 | */ 38 | @Before("daoAspect()") 39 | public void switchDataSource(JoinPoint point) { 40 | Boolean isQueryMethod = isQueryMethod(point.getSignature().getName()); 41 | if (isQueryMethod) { 42 | DynamicDataSourceContextHolder.useSlaveDataSource(); 43 | logger.debug("Switch DataSource to [{}] in Method [{}]", 44 | DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature()); 45 | } 46 | } 47 | 48 | /** 49 | * Restore DataSource 50 | * 51 | * @param point the point 52 | */ 53 | @After("daoAspect()") 54 | public void restoreDataSource(JoinPoint point) { 55 | DynamicDataSourceContextHolder.clearDataSourceKey(); 56 | logger.debug("Restore DataSource to [{}] in Method [{}]", 57 | DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature()); 58 | } 59 | 60 | 61 | /** 62 | * Judge if method start with query prefix 63 | * 64 | * @param methodName 65 | * @return 66 | */ 67 | private Boolean isQueryMethod(String methodName) { 68 | for (String prefix : QUERY_PREFIX) { 69 | if (methodName.startsWith(prefix)) { 70 | return true; 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/DynamicDataSourceContextHolder.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | 4 | import cn.com.hellowood.dynamicdatasource.common.DataSourceKey; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * Multiple DataSource Context Holder 13 | * 14 | * @author HelloWood 15 | * @date 2017 -08-15 14:26 16 | * @Email hellowoodes @gmail.com 17 | */ 18 | public class DynamicDataSourceContextHolder { 19 | 20 | private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); 21 | 22 | private static int counter = 0; 23 | 24 | /** 25 | * Maintain variable for every thread, to avoid effect other thread 26 | */ 27 | private static final ThreadLocal CONTEXT_HOLDER = ThreadLocal.withInitial(DataSourceKey.master::name); 28 | 29 | 30 | /** 31 | * All DataSource List 32 | */ 33 | public static List dataSourceKeys = new ArrayList<>(); 34 | 35 | /** 36 | * The constant slaveDataSourceKeys. 37 | */ 38 | public static List slaveDataSourceKeys = new ArrayList<>(); 39 | 40 | /** 41 | * To switch DataSource 42 | * 43 | * @param key the key 44 | */ 45 | public static void setDataSourceKey(String key) { 46 | CONTEXT_HOLDER.set(key); 47 | } 48 | 49 | /** 50 | * Use master data source. 51 | */ 52 | public static void useMasterDataSource() { 53 | CONTEXT_HOLDER.set(DataSourceKey.master.name()); 54 | } 55 | 56 | /** 57 | * Use slave data source. 58 | */ 59 | public static void useSlaveDataSource() { 60 | try { 61 | int datasourceKeyIndex = counter % slaveDataSourceKeys.size(); 62 | CONTEXT_HOLDER.set(String.valueOf(slaveDataSourceKeys.get(datasourceKeyIndex))); 63 | counter++; 64 | } catch (Exception e) { 65 | logger.error("Switch slave datasource failed, error message is {}", e.getMessage()); 66 | useMasterDataSource(); 67 | e.printStackTrace(); 68 | } 69 | } 70 | 71 | /** 72 | * Get current DataSource 73 | * 74 | * @return data source key 75 | */ 76 | public static String getDataSourceKey() { 77 | return CONTEXT_HOLDER.get(); 78 | } 79 | 80 | /** 81 | * To set DataSource as default 82 | */ 83 | public static void clearDataSourceKey() { 84 | CONTEXT_HOLDER.remove(); 85 | } 86 | 87 | /** 88 | * Check if give DataSource is in current DataSource list 89 | * 90 | * @param key the key 91 | * @return boolean boolean 92 | */ 93 | public static boolean containDataSourceKey(String key) { 94 | return dataSourceKeys.contains(key); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/DynamicRoutingDataSource.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 6 | 7 | /** 8 | * Multiple DataSource Configurer 9 | * 10 | * @author HelloWood 11 | * @date 2017-08-15 11:37 12 | * @Email hellowoodes@gmail.com 13 | */ 14 | 15 | public class DynamicRoutingDataSource extends AbstractRoutingDataSource { 16 | 17 | private final Logger logger = LoggerFactory.getLogger(getClass()); 18 | 19 | /** 20 | * Set dynamic DataSource to Application Context 21 | * 22 | * @return 23 | */ 24 | @Override 25 | protected Object determineCurrentLookupKey() { 26 | logger.debug("Current DataSource is [{}]", DynamicDataSourceContextHolder.getDataSourceKey()); 27 | return DynamicDataSourceContextHolder.getDataSourceKey(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/configuration/WebMvcConfigurer.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.configuration; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.config.BaseWebMvcConfig; 4 | import cn.com.hellowood.dynamicdatasource.apiutil.exception.BaseExceptionHandler; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | 9 | /** 10 | * Config for application 11 | * 12 | * @author HelloWood 13 | * @date 2017-07-11 21:35 14 | * @Email hellowoodes@gmail.com 15 | */ 16 | 17 | @Configuration 18 | public class WebMvcConfigurer extends BaseWebMvcConfig { 19 | 20 | @Bean 21 | public BaseExceptionHandler baseExceptionHandler() { 22 | return new BaseExceptionHandler(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/controller/BaseController.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.controller; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RequestMethod; 5 | import org.springframework.web.bind.annotation.ResponseBody; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | /** 9 | * Base controller 10 | * 11 | * @author HelloWood 12 | * @date 2017-09-25 13:31 13 | * @Email hellowoodes@gmail.com 14 | */ 15 | 16 | @RestController 17 | public class BaseController { 18 | 19 | /** 20 | * Root path, The HEAD method is for SpringBoot Admin to monitor application status 21 | * 22 | * @return 23 | */ 24 | @RequestMapping(value = "/", method = {RequestMethod.GET, RequestMethod.HEAD}) 25 | @ResponseBody 26 | public String root() { 27 | return "Hello World"; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.controller; 2 | 3 | import cn.com.hellowood.dynamicdatasource.apiutil.annotation.ApiResponseBody; 4 | import cn.com.hellowood.dynamicdatasource.model.Product; 5 | import cn.com.hellowood.dynamicdatasource.service.ProductService; 6 | import cn.com.hellowood.dynamicdatasource.error.ServiceException; 7 | import org.springframework.web.bind.annotation.*; 8 | 9 | import javax.annotation.Resource; 10 | import java.util.List; 11 | 12 | /** 13 | * Product controller 14 | * 15 | * @author HelloWood 16 | * @date 2017-07-11 11:38 17 | * @Email hellowoodes@gmail.com 18 | */ 19 | 20 | @RestController 21 | @RequestMapping("/product") 22 | public class ProductController { 23 | 24 | @Resource 25 | private ProductService productService; 26 | 27 | /** 28 | * Get product by id 29 | * 30 | * @param productId 31 | * @return 32 | * @throws ServiceException 33 | */ 34 | @GetMapping("/{id}") 35 | @ApiResponseBody 36 | public Product getProduct(@PathVariable("id") Long productId) throws ServiceException { 37 | return productService.select(productId); 38 | } 39 | 40 | /** 41 | * Get all product 42 | * 43 | * @return 44 | * @throws ServiceException 45 | */ 46 | @GetMapping 47 | @ApiResponseBody 48 | public List getAllProduct() { 49 | return productService.getAllProduct(); 50 | } 51 | 52 | /** 53 | * Update product by id 54 | * 55 | * @param productId 56 | * @param newProduct 57 | * @return 58 | * @throws ServiceException 59 | */ 60 | 61 | @PutMapping("/{id}") 62 | @ApiResponseBody 63 | public Product updateProduct(@PathVariable("id") Long productId, @RequestBody Product newProduct) throws ServiceException { 64 | return productService.update(productId, newProduct); 65 | } 66 | 67 | /** 68 | * Delete product by id 69 | * 70 | * @param productId 71 | * @return 72 | * @throws ServiceException 73 | */ 74 | @DeleteMapping("/{id}") 75 | @ApiResponseBody 76 | public boolean deleteProduct(@PathVariable("id") long productId) throws ServiceException { 77 | return productService.delete(productId); 78 | } 79 | 80 | /** 81 | * Save product 82 | * 83 | * @param newProduct 84 | * @return 85 | * @throws ServiceException 86 | */ 87 | @PostMapping 88 | @ApiResponseBody 89 | public boolean addProduct(@RequestBody Product newProduct) throws ServiceException { 90 | return productService.add(newProduct); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/error/ServiceException.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.error; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ResponseStatus; 5 | 6 | /** 7 | * For handler not expected status 8 | * 9 | * @author HelloWood 10 | * @date 2017-07-11 12:18 11 | * @Email hellowoodes@gmail.com 12 | */ 13 | 14 | @ResponseStatus(HttpStatus.NOT_FOUND) 15 | public class ServiceException extends Exception { 16 | 17 | public ServiceException(String msg, Exception e) { 18 | super(msg + "\n" + e.getMessage()); 19 | } 20 | 21 | public ServiceException(String msg) { 22 | super(msg); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/mapper/ProductDao.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.mapper; 2 | 3 | import cn.com.hellowood.dynamicdatasource.model.Product; 4 | import org.apache.ibatis.annotations.Mapper; 5 | import org.apache.ibatis.annotations.Param; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Product mapper for operate data of products table 11 | * 12 | * @author HelloWood 13 | * @date 2017-07-11 10:54 14 | * @Email hellowoodes@gmail.com 15 | */ 16 | 17 | @Mapper 18 | public interface ProductDao { 19 | Product select(@Param("id") long id); 20 | 21 | Integer update(Product product); 22 | 23 | Integer insert(Product product); 24 | 25 | Integer delete(long productId); 26 | 27 | List getAllProduct(); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/model/Product.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.model; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * Product bean 7 | * 8 | * @author HelloWood 9 | * @date 2017-07-11 11:09 10 | * @Email hellowoodes@gmail.com 11 | */ 12 | public class Product implements Serializable { 13 | private static final long serialVersionUID = 1435515995276255188L; 14 | 15 | private long id; 16 | private String name; 17 | private long price; 18 | 19 | public long getId() { 20 | return id; 21 | } 22 | 23 | public void setId(long id) { 24 | this.id = id; 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 long getPrice() { 36 | return price; 37 | } 38 | 39 | public void setPrice(long price) { 40 | this.price = price; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/service/ProductService.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.service; 2 | 3 | import cn.com.hellowood.dynamicdatasource.mapper.ProductDao; 4 | import cn.com.hellowood.dynamicdatasource.model.Product; 5 | import cn.com.hellowood.dynamicdatasource.error.ServiceException; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.dao.DataAccessException; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Product service for handler logic of product operation 15 | * 16 | * @author HelloWood 17 | * @date 2017-07-11 11:58 18 | * @Email hellowoodes@gmail.com 19 | */ 20 | 21 | @Service 22 | public class ProductService { 23 | 24 | @Autowired 25 | private ProductDao productDao; 26 | 27 | /** 28 | * Get product by id 29 | * If not found product will throw ServiceException 30 | * 31 | * @param productId 32 | * @return 33 | * @throws ServiceException 34 | */ 35 | public Product select(long productId) throws ServiceException { 36 | Product product = productDao.select(productId); 37 | if (product == null) { 38 | throw new ServiceException("Product:" + productId + " not found"); 39 | } 40 | return product; 41 | } 42 | 43 | /** 44 | * Update product by id 45 | * If update failed will throw ServiceException 46 | * 47 | * @param productId 48 | * @param newProduct 49 | * @return 50 | * @throws ServiceException 51 | */ 52 | @Transactional(rollbackFor = DataAccessException.class) 53 | public Product update(long productId, Product newProduct) throws ServiceException { 54 | 55 | if (productDao.update(newProduct) <= 0) { 56 | throw new ServiceException("Update product:" + productId + "failed"); 57 | } 58 | return newProduct; 59 | } 60 | 61 | /** 62 | * Add product to DB 63 | * 64 | * @param newProduct 65 | * @return 66 | * @throws ServiceException 67 | */ 68 | @Transactional(rollbackFor = DataAccessException.class) 69 | public boolean add(Product newProduct) throws ServiceException { 70 | Integer num = productDao.insert(newProduct); 71 | if (num <= 0) { 72 | throw new ServiceException("Add product failed"); 73 | } 74 | return true; 75 | } 76 | 77 | /** 78 | * Delete product from DB 79 | * 80 | * @param productId 81 | * @return 82 | * @throws ServiceException 83 | */ 84 | @Transactional(rollbackFor = DataAccessException.class) 85 | public boolean delete(long productId) throws ServiceException { 86 | Integer num = productDao.delete(productId); 87 | if (num <= 0) { 88 | throw new ServiceException("Delete product:" + productId + "failed"); 89 | } 90 | return true; 91 | } 92 | 93 | /** 94 | * Get all product 95 | * 96 | * @return 97 | */ 98 | public List getAllProduct() { 99 | return productDao.getAllProduct(); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/utils/ApplicationContextHolder.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.utils; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * @author HelloWood 10 | * @date 2017-07-11 10:37 11 | * @Email hellowoodes@gmail.com 12 | */ 13 | 14 | @Component 15 | public class ApplicationContextHolder implements ApplicationContextAware { 16 | 17 | private static ApplicationContext applicationContext; 18 | 19 | @Override 20 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 21 | ApplicationContextHolder.applicationContext = applicationContext; 22 | } 23 | 24 | /** 25 | * Get application context from everywhere 26 | * 27 | * @return 28 | */ 29 | public static ApplicationContext getApplicationContext() { 30 | return applicationContext; 31 | } 32 | 33 | 34 | /** 35 | * Get bean by class name 36 | * 37 | * @param name 38 | * @param 39 | * @return 40 | */ 41 | public static T getBean(String name) { 42 | return (T) applicationContext.getBean(name); 43 | } 44 | 45 | /** 46 | * Get bean by class 47 | * 48 | * @param clazz 49 | * @param 50 | * @return 51 | */ 52 | public static T getBean(Class clazz) { 53 | return applicationContext.getBean(clazz); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/utils/HttpLog.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.utils; 2 | 3 | import org.aspectj.lang.JoinPoint; 4 | import org.aspectj.lang.annotation.*; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.web.context.request.RequestContextHolder; 9 | import org.springframework.web.context.request.ServletRequestAttributes; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | 13 | 14 | /** 15 | * @author HelloWood 16 | * @date 2017-07-30 22:26 17 | * @email hellowoodes@gmail.com 18 | **/ 19 | 20 | @Aspect 21 | @Component 22 | public class HttpLog { 23 | 24 | public static final Logger logger = LoggerFactory.getLogger(HttpLog.class); 25 | 26 | ThreadLocal startTime = new ThreadLocal<>(); 27 | 28 | @Pointcut("execution(public * cn.com.hellowood.dynamicdatasource.controller.*.*(..))") 29 | public void httpLog() { 30 | 31 | } 32 | 33 | @Before("httpLog()") 34 | public void doBefore(JoinPoint joinPoint) { 35 | startTime.set(System.currentTimeMillis()); 36 | 37 | ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 38 | HttpServletRequest request = attributes.getRequest(); 39 | //URL 40 | logger.debug("url:{}", request.getRequestURL()); 41 | //Request method 42 | logger.debug("method:{}", request.getMethod()); 43 | //IP 44 | logger.debug("ip:{}", request.getRemoteAddr()); 45 | //Class method name 46 | logger.debug("method:{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); 47 | // Argument 48 | logger.debug("args:{}", JSONUtil.toJSONString(joinPoint.getArgs())); 49 | } 50 | 51 | @After("httpLog()") 52 | public void doAfter() { 53 | logger.debug("request cost time:{} ms", System.currentTimeMillis() - startTime.get()); 54 | } 55 | 56 | @AfterReturning(returning = "object", pointcut = "httpLog()") 57 | public void afterReturning(Object object) { 58 | logger.debug("response:{}", JSONUtil.toJSONString(object)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/cn/com/hellowood/dynamicdatasource/utils/JSONUtil.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource.utils; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.text.SimpleDateFormat; 10 | 11 | 12 | /** 13 | * JSON data util, for parse and generate JSON data 14 | * 15 | * @author HelloWood 16 | * @date 2017-07-11 16:11 17 | * @Email hellowoodes@gmail.com 18 | */ 19 | 20 | 21 | public class JSONUtil { 22 | 23 | private static final Logger logger = LoggerFactory.getLogger(JSONUtil.class); 24 | 25 | /** 26 | * Transfer object to JSON string 27 | * 28 | * @param object 29 | * @return 30 | */ 31 | public static String toJSONString(Object object) { 32 | String result = null; 33 | ObjectMapper objectMapper = new ObjectMapper(); 34 | //set config of JSON 35 | objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);// can use single quote 36 | objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);//allow unquoted field names 37 | objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));//set date format 38 | 39 | try { 40 | result = objectMapper.writeValueAsString(object); 41 | } catch (JsonProcessingException e) { 42 | logger.error("Generate JSON String error!" + e.getMessage()); 43 | e.printStackTrace(); 44 | } 45 | return result; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.type=com.zaxxer.hikari.HikariDataSource 2 | # Master datasource config 3 | spring.datasource.hikari.master.name=master 4 | spring.datasource.hikari.master.driver-class-name=com.mysql.jdbc.Driver 5 | spring.datasource.hikari.master.jdbc-url=jdbc:mysql://localhost/product_master?useSSL=false 6 | spring.datasource.hikari.master.port=3306 7 | spring.datasource.hikari.master.username=root 8 | spring.datasource.hikari.master.password=123456 9 | 10 | # SlaveAlpha datasource config 11 | spring.datasource.hikari.slave-alpha.name=SlaveAlpha 12 | spring.datasource.hikari.slave-alpha.driver-class-name=com.mysql.jdbc.Driver 13 | spring.datasource.hikari.slave-alpha.jdbc-url=jdbc:mysql://localhost/product_slave_alpha?useSSL=false 14 | spring.datasource.hikari.slave-alpha.port=3306 15 | spring.datasource.hikari.slave-alpha.username=root 16 | spring.datasource.hikari.slave-alpha.password=123456 17 | 18 | # SlaveBeta datasource config 19 | spring.datasource.hikari.slave-beta.name=SlaveBeta 20 | spring.datasource.hikari.slave-beta.driver-class-name=com.mysql.jdbc.Driver 21 | spring.datasource.hikari.slave-beta.jdbc-url=jdbc:mysql://localhost/product_slave_beta?useSSL=false 22 | spring.datasource.hikari.slave-beta.port=3306 23 | spring.datasource.hikari.slave-beta.username=root 24 | spring.datasource.hikari.slave-beta.password=123456 25 | 26 | # SlaveGamma datasource config 27 | spring.datasource.hikari.slave-gamma.name=SlaveGamma 28 | spring.datasource.hikari.slave-gamma.driver-class-name=com.mysql.jdbc.Driver 29 | spring.datasource.hikari.slave-gamma.jdbc-url=jdbc:mysql://localhost/product_slave_gamma?useSSL=false 30 | spring.datasource.hikari.slave-gamma.port=3306 31 | spring.datasource.hikari.slave-gamma.username=root 32 | spring.datasource.hikari.slave-gamma.password=123456 33 | 34 | spring.aop.proxy-target-class=true 35 | 36 | 37 | # MyBatis config 38 | mybatis.type-aliases-package=cn.com.hellowood.dynamicdatasource.mapper 39 | mybatis.mapper-locations=mappers/**Mapper.xml 40 | server.port=9999 41 | spring.mvc.throw-exception-if-no-handler-found=true 42 | 43 | -------------------------------------------------------------------------------- /src/main/resources/db/schema.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE IF EXISTS product_master; 2 | CREATE DATABASE product_master; 3 | CREATE TABLE product_master.product( 4 | id INT PRIMARY KEY AUTO_INCREMENT, 5 | name VARCHAR(50) NOT NULL, 6 | price DOUBLE(10,2) NOT NULL DEFAULT 0 7 | ); 8 | INSERT INTO product_master.product (name, price) VALUES('master', '1'); 9 | 10 | 11 | DROP DATABASE IF EXISTS product_slave_alpha; 12 | CREATE DATABASE product_slave_alpha; 13 | CREATE TABLE product_slave_alpha.product( 14 | id INT PRIMARY KEY AUTO_INCREMENT, 15 | name VARCHAR(50) NOT NULL, 16 | price DOUBLE(10,2) NOT NULL DEFAULT 0 17 | ); 18 | INSERT INTO product_slave_alpha.product (name, price) VALUES('slaveAlpha', '1'); 19 | 20 | DROP DATABASE IF EXISTS product_slave_beta; 21 | CREATE DATABASE product_slave_beta; 22 | CREATE TABLE product_slave_beta.product( 23 | id INT PRIMARY KEY AUTO_INCREMENT, 24 | name VARCHAR(50) NOT NULL, 25 | price DOUBLE(10,2) NOT NULL DEFAULT 0 26 | ); 27 | INSERT INTO product_slave_beta.product (name, price) VALUES('slaveBeta', '1'); 28 | 29 | DROP DATABASE IF EXISTS product_slave_gamma; 30 | CREATE DATABASE product_slave_gamma; 31 | CREATE TABLE product_slave_gamma.product( 32 | id INT PRIMARY KEY AUTO_INCREMENT, 33 | name VARCHAR(50) NOT NULL, 34 | price DOUBLE(10,2) NOT NULL DEFAULT 0 35 | ); 36 | INSERT INTO product_slave_gamma.product (name, price) VALUES('slaveGamma', '1'); -------------------------------------------------------------------------------- /src/main/resources/mappers/ProductMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 17 | 18 | 22 | 23 | 24 | UPDATE product 25 | SET name = #{name}, price = #{price} 26 | WHERE id = #{id} 27 | LIMIT 1 28 | 29 | 30 | 31 | DELETE FROM product 32 | WHERE id = #{id} 33 | LIMIT 1 34 | 35 | 36 | 37 | INSERT INTO product (name, price) VALUES (#{name}, #{price}); 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/test/java/cn/com/hellowood/dynamicdatasource/DynamicDataSourceApplicationTests.java: -------------------------------------------------------------------------------- 1 | package cn.com.hellowood.dynamicdatasource; 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 DynamicDataSourceApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------