赞
踩
先配置配置文件
然后再Application类上加入: @SpringBootApplication( exclude = { DataSourceAutoConfiguration.class } ) //这个注解去除掉默认的数据库配置,然后我们自己去配置database. DataSourceConfig类: 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 org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; /** * db配置类 * @Description: */ @Configuration public class DataSourceConfig { @Bean(name = "db") @ConfigurationProperties(prefix = "spring.datasource.db") public DataSource dataSource1() { return DataSourceBuilder.create().build(); } @Bean(name = "db2") @ConfigurationProperties(prefix = "spring.datasource.db2") public DataSource dataSource2() { return DataSourceBuilder.create().build(); } /** * 动态数据源: 通过AOP在不同数据源之间动态切换 * * @return */ @Primary @Bean(name = "dynamicDS1") public DataSource dataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); // 默认数据源 dynamicDataSource.setDefaultTargetDataSource(dataSource1()); // 配置多数据源 Map<Object, Object> dsMap = new HashMap(5); dsMap.put("db", dataSource1()); dsMap.put("db2", dataSource2()); dynamicDataSource.setTargetDataSources(dsMap); return dynamicDataSource; } /** * 配置@Transactional注解事物 * @return */ @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } } DynamicDataSource 类 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; /** * 异步默认db */ public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDB(); } } DynamicDataSourceAspect 类 import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Method; /** * 切面切换db */ @Aspect @Component public class DynamicDataSourceAspect { @Before("@annotation(DS)") public void beforeSwitchDS(JoinPoint point){ //获得当前访问的class Class<?> className = point.getTarget().getClass(); //获得访问的方法名 String methodName = point.getSignature().getName(); //得到方法的参数的类型 Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes(); String dataSource = DataSourceContextHolder.DEFAULT_DS; try { // 得到访问的方法对象 Method method = className.getMethod(methodName, argClass); // 判断是否存在@DS注解 if (method.isAnnotationPresent(DS.class)) { DS annotation = method.getAnnotation(DS.class); // 取出注解中的数据源名 dataSource = annotation.value(); } } catch (Exception e) { e.printStackTrace(); } // 切换数据源 DataSourceContextHolder.setDB(dataSource); } @After("@annotation(DS)") public void afterSwitchDS(JoinPoint point){ DataSourceContextHolder.clearDB(); } } DataSourceContextHolder 类 public class DataSourceContextHolder { /** * 默认数据源 */ public static final String DEFAULT_DS = "db"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); // 设置数据源名 public static void setDB(String dbType) { contextHolder.set(dbType); } // 获取数据源名 public static String getDB() { return (contextHolder.get()); } // 清除数据源名 public static void clearDB() { contextHolder.remove(); } } DS 类 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Description: 自定义注解 */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD }) public @interface DS { String value() default "db"; } 注意:默认的数据库在调用的时候不用加任何的东西,按照正常的方式去使用即可,而使用到第二个数据库的serviceImpl的方法上加上 @DS("db2")即可,这样这个方法中的mapper文件就会调用不是默认的那个数据库了。 第二种方案: pom.xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 数据库连接池 start --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency> <!-- 数据库连接池 end --> application.propertiues spring: datasource: #master名字是自定义的,跟配置文件有关 master: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1/test1?useUnicode=true&characterEncoding=utf- 8&serverTimezone=UTC&useSSL=true&allowMultiQueries=true username: root password: root #同上 slaver: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1/test2?useUnicode=true&characterEncoding=utf- 8&serverTimezone=UTC&useSSL=true&allowMultiQueries=true username: root password: root 主数据源 @Configuration //这里的包是你的接口,xml 数据源 接口 绑定到一起 @MapperScan(basePackages = "com.xxx.mapper.master", sqlSessionTemplateRef = "masterSqlSessionTemplate") public class MasterDataSourceConfiguration { //连接yml配置 master @Value("${spring.datasource.master.driver-class-name}") private String driverClassName; @Value("${spring.datasource.master.url}") private String url; @Value("${spring.datasource.master.username}") private String username; @Value("${spring.datasource.master.password}") private String password; @Bean(name = "masterDataSource") @Primary public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(this.driverClassName); dataSource.setUrl(this.url); dataSource.setUsername(this.username); dataSource.setPassword(this.password); return dataSource; } @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //mybatis 的 xml绑定 bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/master/*Mapper.xml")); return bean.getObject(); } @Bean(name = "masterTransactionManager") @Primary public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "masterSqlSessionTemplate") @Primary public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } 次数据源 @Configuration @MapperScan(basePackages = "com.xxx.mapper.salver", sqlSessionTemplateRef = "slaverSqlSessionTemplate") public class SlaverDataSourceConfiguration { @Value("${spring.datasource.slaver.driver-class-name}") private String driverClassName; @Value("${spring.datasource.slaver.url}") private String url; @Value("${spring.datasource.slaver.username}") private String username; @Value("${spring.datasource.slaver.password}") private String password; @Bean(name = "slaverDataSource") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(this.driverClassName); dataSource.setUrl(this.url); dataSource.setUsername(this.username); dataSource.setPassword(this.password); return dataSource; } @Bean(name = "slaverSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("slaverDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/slaver/*Mapper.xml")); return bean.getObject(); } @Bean(name = "slaverTransactionManager") public DataSourceTransactionManager transactionManager(@Qualifier("slaverDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "slaverSqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaverSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。