1、首先配置yml配置文件:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
master:
url: jdbc:mysql://192.168.145.145:3306/gourd?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
slave:
url: jdbc:mysql://192.168.145.146:3306/gourd?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
druid:
initial-size: 5
max-wait: 60000
min-idle: 1
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements: 50
max-pool-prepared-statement-per-connection-size: 20
如果只有一个数据库,master和slave配置成一样即可;
如果有两个数据库,数据库需配置主从复制,参考:https://blog.csdn.net/HXNLYW/article/details/90373149
数据库密码加密:https://blog.csdn.net/HXNLYW/article/details/98635913
druid依赖包:
<!--Druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
2、定义主从数据库名
import lombok.Data;
/**
* @author gourd
*/
@Data
public class CommonConstant {
/**
* 主数据源
*/
public static final String MASTER_DATASOURCE = "masterDruidDataSource";
/**
* 从数据源
*/
public static final String SLAVE_DATASOURCE= "slaveDruidDataSource";
}
3、定义目标数据库注解及AOP切面
import com.gourd.common.constant.CommonConstant;
import java.lang.annotation.*;
/**
* @program: springboot
* @description: 动态切换数据源注解
* @author: gourd
* @date: 2018-11-22 14:02
* @since: 1.0
**/
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
String value() default CommonConstant.MASTER_DATASOURCE;
// //代码切换到数据源
// DynamicDataSource.setDataSource(CommonConstant.MASTER_DATASOURCE);
// DynamicDataSource.clearDataSource();
}
import com.gourd.base.annotation.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* @program: springboot
* @description: 动态切换数据源AOP切面处理
* @author: gourd
* @date: 2018-11-22 14:03
* @since: 1.0
**/
@Aspect
@Component
@Slf4j
public class DataSourceAspect implements Ordered {
/**
* 切点: 所有配置 TargetDataSource 注解的方法
*/
@Pointcut("@annotation(com.gourd.base.annotation.TargetDataSource)")
public void dataSourcePointCut() {}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
TargetDataSource ds = method.getAnnotation(TargetDataSource.class);
// 通过判断 @ChangeDataSource注解 中的值来判断当前方法应用哪个数据源
DynamicDataSource.setDataSource(ds.value());
log.info("^o^= 当前数据源: " + ds.value());
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
log.debug("^o^= clean datasource");
}
}
@Override
public int getOrder() {
return 1;
}
}
4、动态数据源创建:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
/**
* @program: springboot
* @description: 创建动态数据源
* 实现数据源切换的功能就是自定义一个类扩展AbstractRoutingDataSource抽象类,
* 其实该相当于数据源DataSourcer的路由中介,
* 可以实现在项目运行时根据相应key值切换到对应的数据源DataSource上。
* @author: gourd
* @date: 2018-11-22 13:59
* @since: 1.0
**/
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
/**
* 配置DataSource, defaultTargetDataSource为主数据库
*/
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
//设置默认数据源
super.setDefaultTargetDataSource(defaultTargetDataSource);
//设置数据源列表
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
/**
* 是实现数据源切换要扩展的方法,
* 该方法的返回值就是项目中所要用的DataSource的key值,
* 拿到该key后就可以在resolvedDataSource中取出对应的DataSource,
* 如果key找不到对应的DataSource就使用默认的数据源。
* */
@Override
protected Object determineCurrentLookupKey() {
return getDataSource();
}
/**
* 绑定当前线程数据源路由的key
* 使用完成后必须调用removeRouteKey()方法删除
*/
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
/**
* 获取当前线程的数据源路由的key
*/
public static String getDataSource() {
return contextHolder.get();
}
/**
* 删除与当前线程绑定的数据源路由的key
*/
public static void clearDataSource() {
contextHolder.remove();
}
}
5、动态数据源配置类:
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.gourd.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;
/**
* @program: springboot
* @description: 动态数据源配置
* @author: gourd
* @date: 2018-11-22 14:01
* @since: 1.0
**/
@Configuration
@Slf4j
public class DynamicDataSourceConfig {
/**
* 创建 TargetDataSource Bean
*/
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
DataSource dataSource = DruidDataSourceBuilder.create().build();
return dataSource;
}
@Bean
@ConfigurationProperties("spring.datasource.slave")
public DataSource slaveDataSource() {
DataSource dataSource = DruidDataSourceBuilder.create().build();
return dataSource;
}
/**
* 如果还有数据源,在这继续添加 TargetDataSource Bean
*/
@Bean
@Primary
public DynamicDataSource dataSource(DataSource masterDataSource, DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(2);
targetDataSources.put(CommonConstant.MASTER_DATASOURCE, masterDataSource);
targetDataSources.put(CommonConstant.SLAVE_DATASOURCE, slaveDataSource);
// 还有数据源,在targetDataSources中继续添加
log.info("^o^= DataSources:" + targetDataSources);
//默认的数据源是oneDataSource
return new DynamicDataSource(masterDataSource, targetDataSources);
}
}
6、以上就已经配置完成了读写分离,下面是用法:
1)方法上加注解
@Override
@TargetDataSource(DataSourceNames.SLAVE_DATASOURCE)
public ResponseUserToken login(String username, String password) {
}
2)代码中切换数据源,默认主数据源:
//代码切换到数据源
DynamicDataSource.setDataSource(DataSourceNames.SLAVE_DATASOURCE);
有兴趣的小伙伴可以下载源码项目:https://blog.csdn.net/HXNLYW/article/details/98037354