一.原理
1.基于互聯(lián)網(wǎng)背景,服務響應需要越來越快,從而衍生出讀寫分離,即讓主數(shù)據(jù)庫(master)處理事務性增、改、刪操作(INSERT、UPDATE、DELETE),而從數(shù)據(jù)庫(slave)處理SELECT查詢操作;
2.避免慢查詢長期占用鏈接,導致插入時變慢;或者避免插入時過慢影響查詢速度;
3.主數(shù)據(jù)庫只做修改,從服務器只做查詢,同時主服務器的修改需要同步到從服務器。
4.服務啟動時,配置好主從數(shù)據(jù)源,執(zhí)行方法時根據(jù)注解ReadOnly選擇從庫(讀庫)數(shù)據(jù)源,默認選擇主庫(修改)數(shù)據(jù)源。
二代碼框架
1.工程結(jié)構(gòu)
mysql讀寫分離插件代碼結(jié)構(gòu)
2.讀數(shù)據(jù)庫注解定義
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnly {
}
3.數(shù)據(jù)庫名稱本地線程池設(shè)置
public class DbContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDbContext(String dbName) {
if (dbName == null || "".equals(dbName)) {
throw new NullPointerException();
}
contextHolder.set(dbName);
}
public static String getDbContext() {
return contextHolder.get();
}
public static void removeDbContext() {
contextHolder.remove();
}
}
4.動態(tài)數(shù)據(jù)源選擇類
public class RoutingDataSource extends AbstractRoutingDataSource {
private static final Logger LOG = LoggerFactory.getLogger(DBRouterAop.class);
@Override
public DataSource determineTargetDataSource() {
return super.determineTargetDataSource();
}
@Override
protected Object determineCurrentLookupKey() {
String dbName = DbContextHolder.getDbContext();
LOG.info("target database source is " + (dbName == null ? "default datasource" : dbName));
return dbName;
}
}
5.數(shù)據(jù)源配置類
@Configuration
public class DataSourceConfig {
@Autowired
@Qualifier("master")
private DbProperties master;
@Autowired
@Qualifier("slave")
private DbProperties slave;
@Bean
public RoutingDataSource routingDataSource() {
RoutingDataSource routingDataSource = new RoutingDataSource();
Map<Object, Object> targetDataSources = new HashMap<>();
//master
DataSource masterDatasource = getDataSource(master);
targetDataSources.put(DbType.MASTER.name(), masterDatasource);
routingDataSource.setDefaultTargetDataSource(masterDatasource);
//slave
DataSource slaveDatasource = getDataSource(slave);
targetDataSources.put(DbType.SLAVE.name(), slaveDatasource);
routingDataSource.setTargetDataSources(targetDataSources);
routingDataSource.afterPropertiesSet();
return routingDataSource;
}
private DataSource getDataSource(DbProperties properties) {
return new DriverManagerDataSource(properties.getUrl(), properties.getUsername(), properties.getPassword());
}
}
6.切面選擇方法執(zhí)行時選擇的數(shù)據(jù)源
@Aspect
@Component
public class DBRouterAop {
@Around(value = "@annotation(readOnly)")
public Object proceed(ProceedingJoinPoint pjp, ReadOnly readOnly) throws Throwable {
try {
DbContextHolder.setDbContext(DbType.SLAVE.name());
Object result = pjp.proceed();
return result;
} finally {
DbContextHolder.removeDbContext();
}
}
}
7.pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>datasource-router-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
三.測試驗證
1.依賴讀寫分離插件
<dependency>
<groupId>org.example</groupId>
<artifactId>datasource-router-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2.配置數(shù)據(jù)源
server:
port: 8081
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:/mybatis/mapper/*.xml
type-aliases-package: com.example.test.infrastructure.po.User
# 數(shù)據(jù)庫配置
db:
master:
url: jdbc:mysql://127.0.0.1:3306/master?useUnicode=true
username: root
password: root123
slave:
url: jdbc:mysql://127.0.0.1:3306/slave?useUnicode=true
username: root
password: root123
3.結(jié)果驗證
1.查詢時數(shù)據(jù)源選擇的時從庫
從庫查詢
2.寫入時數(shù)據(jù)源選擇主庫
主庫寫入