1.创建项目并加入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
2配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
master:
url: jdbc:mysql://192.168.218.128:3306/testcopy?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&tinyInt1isBit=false&allowMultiQueries=true&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
enabled: true
url: jdbc:mysql://192.168.218.129:3306/testcopy?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&tinyInt1isBit=false&allowMultiQueries=true&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
3配置类
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource writer() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource reader() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@Primary
public DynamicDataSource dataSource(DataSource reader, DataSource writer) {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put("read", reader);
targetDataSources.put("write", writer);
return new DynamicDataSource(reader, targetDataSources);
}
}
4.动态数据源
/**
* 动态数据源 DataSource
*/
public final class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultDataSource);
if (null == targetDataSources) {
return;
}
super.setTargetDataSources(targetDataSources);
// afterPropertiesSet()方法调用时用来将targetDataSources的属性写入resolvedDataSources中的
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DataSourceBinding.getDataSource();
}
}
5创建线程私数据源类
@Slf4j
@Component
public class DataSourceBinding {
/**
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
* */
private static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
public static void bindDataSource(String dataSourceType) {
threadLocal.set(dataSourceType);
log.info("切换到{}数据源",dataSourceType);
}
public static String getDataSource() {
return threadLocal.get();
}
public static void clearDataSource() {
threadLocal.remove();
}
}
6.创建切面类
@Aspect
@Component
@Order(1)
public class TestAspect {
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
public Object around(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
String name = signature.getMethod().getName();
if (name.substring(0, 3).equals("get")) {
DataSourceBinding.bindDataSource("read");
}else{
DataSourceBinding.bindDataSource("write");
}
try {
return point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
} finally {
DataSourceBinding.clearDataSource();
}
}
}
7创建启动类进行测试
要注意排除数据源的自动注入
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class TestCopyApplication {
public static void main(String[] args) {
DemoApplication.run("testcopy",TestCopyApplication.class,args);
}
}