springboot+mybatisplus+druid实现读写分离
时间: 2023-09-11 19:06:33 浏览: 129
实现读写分离可以利用 SpringBoot、MybatisPlus 和 Druid 进行配置。下面是一个简单的实现过程:
1. 添加 MybatisPlus 和 Druid 的 Maven 依赖。
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
2. 在配置文件中添加 Druid 数据源相关配置。
```yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initialSize: 5
maxActive: 10
minIdle: 5
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
```
3. 配置 MybatisPlus 的多数据源功能。
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
@Qualifier("slaveDataSource") DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.getType(), masterDataSource);
targetDataSources.put(DataSourceType.SLAVE.getType(), slaveDataSource);
return new DynamicDataSource(masterDataSource, targetDataSources);
}
}
```
4. 创建一个 DataSourceHolder 类,用于保存当前线程的数据源类型。
```java
public class DataSourceHolder {
private static final ThreadLocal<String> HOLDER = new ThreadLocal<>();
public static String getDataSource() {
return HOLDER.get();
}
public static void setDataSource(String dataSource) {
HOLDER.set(dataSource);
}
public static void clearDataSource() {
HOLDER.remove();
}
}
```
5. 创建一个枚举类型 DataSourceType,用于表示数据源类型。
```java
public enum DataSourceType {
MASTER("master"),
SLAVE("slave");
private final String type;
DataSourceType(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
```
6. 创建一个 DynamicDataSource 类,继承 AbstractRoutingDataSource,用于动态切换数据源。
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
private final Map<Object, Object> targetDataSources;
public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultDataSource);
this.targetDataSources = targetDataSources;
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSource();
}
@Override
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
this.targetDataSources.putAll(targetDataSources);
super.setTargetDataSources(this.targetDataSources);
super.afterPropertiesSet();
}
@Override
public void addTargetDataSource(Object key, Object dataSource) {
this.targetDataSources.put(key, dataSource);
super.setTargetDataSources(this.targetDataSources);
super.afterPropertiesSet();
}
}
```
7. 创建一个 AopDataSourceConfig 类,用于配置切面,实现动态切换数据源。
```java
@Configuration
public class AopDataSourceConfig {
@Bean
public DataSourceAspect dataSourceAspect() {
return new DataSourceAspect();
}
}
```
```java
@Aspect
public class DataSourceAspect {
@Pointcut("@annotation(com.example.demo.annotation.Master) " +
"|| execution(* com.example.demo.service..*.select*(..)) " +
"|| execution(* com.example.demo.service..*.get*(..)) " +
"|| execution(* com.example.demo.service..*.query*(..)) " +
"|| execution(* com.example.demo.service..*.find*(..)) " +
"|| execution(* com.example.demo.service..*.count*(..))")
public void read() {
}
@Pointcut("execution(* com.example.demo.service..*.insert*(..)) " +
"|| execution(* com.example.demo.service..*.update*(..)) " +
"|| execution(* com.example.demo.service..*.delete*(..))")
public void write() {
}
@Around("read()")
public Object read(ProceedingJoinPoint joinPoint) throws Throwable {
try {
DataSourceHolder.setDataSource(DataSourceType.SLAVE.getType());
return joinPoint.proceed();
} finally {
DataSourceHolder.clearDataSource();
}
}
@Around("write()")
public Object write(ProceedingJoinPoint joinPoint) throws Throwable {
try {
DataSourceHolder.setDataSource(DataSourceType.MASTER.getType());
return joinPoint.proceed();
} finally {
DataSourceHolder.clearDataSource();
}
}
}
```
8. 在 Service 层的方法上使用 @Master 注解,表示强制使用主库。
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
@Master
public boolean save(User user) {
return super.save(user);
}
}
```
这样就实现了读写分离功能。需要注意的是,在使用 MybatisPlus 进行 CRUD 操作时,需要使用对应的 Service 方法,例如 selectList、selectPage、insert、updateById、deleteById,而不是直接调用 Mapper 方法。否则,数据源切换将不会生效。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)