多源数据库配置
pom文件
<!--因为父工程里面已经有springboot的版本号了 所以子工程都没有添加版本号 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--<!– aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--<!– 数据源选择druid –>-->
<!--<dependency>-->
<!--<groupId>com.alibaba</groupId>-->
<!--<artifactId>druid-spring-boot-starter</artifactId>-->
<!--<version>1.1.24</version>-->
<!--</dependency>-->
application.properties
#数据源1 本文用的 是默认的hikari 数据源 用druid就放开 pom文件引入druid
#datasource.master.type=com.alibaba.druid.pool.DruidDataSource
datasource.master.jdbc-url=jdbc:mysql://ip:3306/dts?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
datasource.master.username=root
datasource.master.password=123456
datasource.master.driver-class-name=com.mysql.jdbc.Driver
##数据源2
#datasource.slave.type=com.alibaba.druid.pool.DruidDataSource
datasource.slave.jdbc-url=jdbc:mysql://ip:3306/pgg?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
datasource.slave.username=root
datasource.slave.password=123456
datasource.slave.driver-class-name=com.mysql.jdbc.Driver
#使用列标签替换别名
mybatis.configuration.map-underscore-to-camel-case=true
#驼峰命名数据库u_id实体类
mybatis.configuration.use-column-label=true
#数据库自增主键值
mybatis.configuration.use-generated-keys=true
#扫描实体类
mybatis.type-aliases-package=com.huwei.entity
#扫描mapper文件
mybatis.mapper-locations=classpath:/mapper/**.xml
#日志打印到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
动态数据源
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @author lazycece
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
private static final ThreadLocal<String> DATA_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("current data-source is {}", key);
return key;
}
}
多数据源
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.*;
/**
* @version 1.0
* @Author BAI
* @Description //多数据源
* @Class MultiDataSource.Class
* @Date 2020/9/27 8:35
*/
@Configuration
public class MultiDataSource {
public static final String MASTER_DATA_SOURCE = "masterDataSource";
public static final String LOG_DATA_SOURCE = "logDataSource";
@Bean(name = MultiDataSource.MASTER_DATA_SOURCE)
@ConfigurationProperties(prefix = "datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = MultiDataSource.LOG_DATA_SOURCE)
@ConfigurationProperties(prefix = "datasource.slave")
public DataSource logDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "dynamicDataSource")
public DynamicDataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
Map<Object, Object> dataSourceMap = new HashMap<>(4);
dataSourceMap.put(MASTER_DATA_SOURCE, masterDataSource());
dataSourceMap.put(LOG_DATA_SOURCE, logDataSource());
dynamicDataSource.setTargetDataSources(dataSourceMap);
return dynamicDataSource;
}
}
annotation
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface DataSource {
String value();
}
aop切换数据源的
/**
* @version 1.0
* @Author BAI
* @Description //TODO
* @Class DataSourceConfig.Class
* @Date 2020/9/27 8:42
*/
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class DataSourceConfig {
@Before("@annotation(dataSource)")
public void beforeSwitchDataSource(DataSource dataSource) {
DynamicDataSource.changeDataSource(dataSource.value());
}
@After("@annotation(DataSource)")
public void afterSwitchDataSource() {
DynamicDataSource.clearDataSource();
}
}
对于需要切换数据源的service 方法添加注解 指定数据源
可以再impl上面添加注解 也可以在dao层方法上面添加注解
public interface StuDao {
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
@DataSource(value = MultiDataSource.LOG_DATA_SOURCE)
Stu queryById(Integer id);
@Service("dtsTaskService")
public class DtsTaskServiceImpl implements DtsTaskService {
@Resource
private DtsTaskDao dtsTaskDao;
/**
* 通过ID查询单条数据
*
* @param id 主键
* @return 实例对象
*/
@Override
@DataSource(value = MultiDataSource.MASTER_DATA_SOURCE)
public DtsTask queryById(String id) {
return this.dtsTaskDao.queryById(id);
}
## 启动类修改注解
@MapperScan("com.bai.springcloud.dao")
/*禁止springboot自动注入数据源配置*/
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableTransactionManagement