1.首先引入依赖
<dependencies>
<!-- springboot核心包-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.20.RELEASE</version>
</dependency>
<!-- springboot-aop包,AOP切面注解,Aspectd等相关注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>1.5.20.RELEASE</version>
</dependency>
<!-- 开发测试环境修改文件实时生效包,生产默认不使用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>1.5.20.RELEASE</version>
<optional>true</optional>
</dependency>
<!-- mysql数据库连接包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- druid连接池引入 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<!-- lombok减少实体类操作 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
</dependencies>
2.Application相关配置
@SpringBootApplication
@EnableAutoConfiguration(exclude={DruidDataSourceAutoConfigure.class})//需要将druid连接池的自动配置关掉,使用我们自己的配置
//@MapperScan(basePackages = {"com.martin.mapper"}) 因为在mapper上添加了@Mapper注解,因此这里没有扫描mapper
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.yml配置
#这里使用了docker开启了两个mysql服务
server:
port: 7788
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
#master
master:
url: jdbc:mysql://192.168.188.128:3339/uqierp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
max-idle: 10
max-wait: 10000
min-idle: 5
initial-size: 5
#从数据库slave
slave:
url: jdbc:mysql://192.168.188.128:3340/uqierp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&allowMultiQueries=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
max-idle: 10
max-wait: 10000
min-idle: 5
initial-size: 5
4.数据源的相关配置
4.1 获取当前线程的数据源对象
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
/**
* @Description: 获取当前使用的是哪个数据源
* @return: java.lang.Object
* @author: martin
* @date: 2020-04-09 18:03
*/
protected Object determineCurrentLookupKey() {
log.info("当前的数据源为:{}",DynamicDataSourceContextHolder.getDbType());
return DynamicDataSourceContextHolder.getDbType();
}
}
4.2 数据源的相关处理操作,主要针对当前线程
@Slf4j
public class DynamicDataSourceContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
/**
* @Description: 设置数据源
* @return:
* @author: martin
* @date: 2020-04-09 17:59
*/
public static void setDbType(DataSourceKey dbType){
contextHolder.set(dbType.getValue());
}
/**
* @Description: 获取当前数据源
* @return:
* @author: martin
* @date: 2020-04-09 17:59
*/
public static String getDbType(){
return (String) contextHolder.get();
}
/**
* @Description: 清除上下文对象
* @return:
* @author: martin
* @date: 2020-04-09 17:59
*/
public static void clearDbType(){
contextHolder.remove();
}
//可以在这里设置随机数访问不同数据库
}
4.3 数据源的配置
@Configuration
public class DynamicDataSourceConfiguration {
//定义master
@Bean(name = "master")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource master(){
return DruidDataSourceBuilder.create().build();
}
//定义slave
@Bean(name = "slave")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slave(){
return DruidDataSourceBuilder.create().build();
}
/**
* @Description: 核心动态数据源
* @return:
* @author: martin
* @date: 2020-04-11 14:16
* 这里注意下两点
1.因为都是DataSouce对象,必须有一个主要对象才能得以运行
2.要使用@Quarlifier标签根据name去找指定的对象
*/
@Bean
@Primary
public DataSource dynamicDataSource(@Qualifier("master") DataSource master, @Qualifier("slave") DataSource slave){
DynamicDataSource dynamicDataSource = new DynamicDataSource();
//设置默认数据源
dynamicDataSource.setDefaultTargetDataSource(master);
//设置指定数据源
Map<Object,Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put(DataSourceKey.master.getValue(), master);
targetDataSources.put(DataSourceKey.slave.getValue(), slave);
dynamicDataSource.setTargetDataSources(targetDataSources);
return dynamicDataSource;
}
//设置sessionFactory
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception{
//这里有两种写法,可以使用sqlSessionFactory是针对普通实现的
//因为我使用的是mybatisplus,因此需要使用MybatisSqlSessionFactoryBean ,先拿到默认的对象再进行设置自定的数据源等操作
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource(master(),slave()));
//配置xml文件读取位置
//指明mapper.xml的位置
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/mapping/**Mapper.xml"));
//指明实体类扫描
sqlSessionFactoryBean.setTypeAliasesPackage("com.martin.entity");
return sqlSessionFactoryBean.getObject();
}
//获取sqlSessionFactory对象,并使用
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
//事务管理
@Bean
public PlatformTransactionManager platformTransactionManager(){
return new DataSourceTransactionManager(dynamicDataSource(master(),slave()));
}
}
5.AOP相关
5.1 声明标签
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
//默认使用master数据源
DataSourceKey dataSourceKey() default DataSourceKey.master;
}
5.2 aspect进行处理
@Slf4j
@Component
@Aspect
@Order(-1)
public class TargetDataSourceAspect {
//指定切点
@Pointcut("execution(* com.martin.service.*.list*(..))")
public void pointCut() {
}
/**
* 执行方法前更换数据源
*
* @param joinPoint 切点
* @param targetDataSource 动态数据源
*/
@Before("@annotation(targetDataSource)")
public void doBefore(JoinPoint joinPoint, TargetDataSource targetDataSource) {
//默认是master
DataSourceKey dataSourceKey = targetDataSource.dataSourceKey();
if (dataSourceKey == DataSourceKey.slave) {
log.info(String.format("设置数据源为 %s", DataSourceKey.slave));
DynamicDataSourceContextHolder.setDbType(DataSourceKey.slave);
} else {
log.info(String.format("使用默认数据源 %s", DataSourceKey.master));
DynamicDataSourceContextHolder.setDbType(DataSourceKey.master);
}
}
/**
* 执行方法后清除数据源设置
*
* @param joinPoint 切点
* @param targetDataSourceAspect 动态数据源
*/
@After("@annotation(targetDataSource)")
public void doAfter(JoinPoint joinPoint, TargetDataSource targetDataSource) {
log.info(String.format("当前数据源 %s 执行清理方法", targetDataSource.dataSourceKey()));
DynamicDataSourceContextHolder.clearDbType();
}
//在切点方法之前判断是否存在标签,如果不存在就默认master
@Before(value = "pointCut()")
public void doBeforeWithSlave(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取当前切点方法对象
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {//判断是否为接口方法
try {
//获取实际类型的方法对象
method = joinPoint.getTarget().getClass()
.getDeclaredMethod(joinPoint.getSignature().getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
log.error("方法不存在!", e);
}
}
if (null == method.getAnnotation(TargetDataSource.class)) {
DynamicDataSourceContextHolder.setDbType(DataSourceKey.master);
}
}
6.实际操作
//在service的方法上使用标签@TargetDataSource指定特定的数据源
@Slf4j
@Service
public class HotelService{
@Resource
private BaseInfoMapper baseInfoMapper;
@Resource
private UserInfoMapper userInfoMapper;
@TargetDataSource(dataSourceKey = DataSourceKey.master)
public void testMaster(){
//使用db1
BaseInfo baseInfo = baseInfoMapper.selectById(1);
int baseCount = baseInfoMapper.listCount();
log.info("master====================baseInfo:{},count:{}",baseInfo,baseCount);
}
@TargetDataSource(dataSourceKey = DataSourceKey.slave)
public void testSlave(){
//使用db2
UserInfo userInfo = userInfoMapper.selectById(1);
int userCount = userInfoMapper.listCount();
log.info("slave====================userInfo:{},userCount:{}",userInfo,userCount);
}