pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent2.1.6.RELEASE com.example demo0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-devtoolsruntime true org.projectlombok lomboktrue org.springframework.boot spring-boot-starter-testtest mysql mysql-connector-java8.0.16 org.springframework.boot spring-boot-starter-webcom.alibaba druid-spring-boot-starter1.1.22 org.mybatis.spring.boot mybatis-spring-boot-starter2.0.1 junit junitorg.aspectj aspectjrt1.9.7 org.aspectj aspectjweaver1.9.7 org.springframework.boot spring-boot-maven-pluginorg.projectlombok lombok
项目结构图
yml文件
server: port: 8086 mybatis: mapperLocations: classpath*:mapper public class DynamicDataSource extends AbstractRoutingDataSource { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class); private static final ThreadLocalDATA_SOURCE_KEY = new ThreadLocal<>(); static void changeDataSource(String dataSourceKey) { DATA_SOURCE_KEY.set(dataSourceKey); } static void clearDataSource() { DATA_SOURCE_KEY.remove(); } @Override protected Object determineCurrentLookupKey() { String key = DATA_SOURCE_KEY.get(); LOGGER.info("切换数据源为: {}", key); return key; } }
4、java配置数据源
package com.example.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; @Configuration public class MultiDataSource { public static final String TB1 = "tb1"; public static final String TB2 = "tb2"; public static final String TB3 = "tb3"; @Bean(name = MultiDataSource.TB1) @ConfigurationProperties(prefix = "spring.datasource.db1") public DataSource tb1() { return DataSourceBuilder.create().build(); } @Bean(name = MultiDataSource.TB2) @ConfigurationProperties(prefix = "spring.datasource.db2") public DataSource tb2() { return DataSourceBuilder.create().build(); } @Bean(name = MultiDataSource.TB3) @ConfigurationProperties(prefix = "spring.datasource.db3") public DataSource tb3() { return DataSourceBuilder.create().build(); } @Primary @Bean(name = "dynamicDataSource") public DynamicDataSource dataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); dynamicDataSource.setDefaultTargetDataSource(tb1()); Map最最主要的是:在service的实现类上面加上注解,下面看我是怎么加的 完事了 ,直接启动,请求:
项目引入jar包图
这个是我自己经过网上东拼西凑,所得的结果,因为网上别人说的不怎么全,现在自己弄出来想记录一下。如果对你们有帮助,那我写这个就更加有意义了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)