1. 引言
讀寫分離要做的事情就是對于一條SQL該選擇哪個數(shù)據(jù)庫去執(zhí)行吧寺,至于誰來做選擇數(shù)據(jù)庫這件事兒刁俭,無非兩個橄仍,要么中間件幫我們做,要么程序自己做牍戚。因此侮繁,一般來講,讀寫分離有兩種實現(xiàn)方式如孝。第一種是依靠中間件(比如:MyCat)宪哩,也就是說應(yīng)用程序連接到中間件,中間件幫我們做SQL分離第晰;第二種是應(yīng)用程序自己去做分離锁孟。這里我們選擇程序自己來做,主要是利用Spring提供的路由數(shù)據(jù)源茁瘦,以及AOP
然而品抽,應(yīng)用程序?qū)用嫒プ鲎x寫分離最大的弱點(不足之處)在于無法動態(tài)增加數(shù)據(jù)庫節(jié)點,因為數(shù)據(jù)源配置都是寫在配置中的甜熔,新增數(shù)據(jù)庫意味著新加一個數(shù)據(jù)源圆恤,必然改配置,并重啟應(yīng)用腔稀。當(dāng)然盆昙,好處就是相對簡單。
2. AbstractRoutingDataSource
基于特定的查找key路由到特定的數(shù)據(jù)源烧颖。它內(nèi)部維護了一組目標數(shù)據(jù)源弱左,并且做了路由key與目標數(shù)據(jù)源之間的映射窄陡,提供基于key查找數(shù)據(jù)源的方法炕淮。
3. 實踐
3.1. maven依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2. 數(shù)據(jù)源配置
application.yml
spring:
datasource:
master:
jdbc-url: jdbc:mysql://localhost:3306/test1
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave1:
jdbc-url: jdbc:mysql://localhost:3306/test2
username: pig # 只讀賬戶
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave2:
jdbc-url: jdbc:mysql://localhost:3306/test3
username: pig # 只讀賬戶
password: 123456
driver-class-name: com.mysql.jdbc.Driver
多數(shù)據(jù)源配置
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.slave1")
public DataSource slave1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.slave2")
public DataSource slave2DataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
@Qualifier("slave1DataSource") DataSource slave1DataSource,
@Qualifier("slave2DataSource") DataSource slave2DataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.MASTER, masterDataSource);
targetDataSources.put(DBTypeEnum.SLAVE1, slave1DataSource);
targetDataSources.put(DBTypeEnum.SLAVE2, slave2DataSource);
MyRoutingDataSource myRoutingDataSource = new MyRoutingDataSource();
myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
myRoutingDataSource.setTargetDataSources(targetDataSources);
return myRoutingDataSource;
}
}
這里,我們配置了4個數(shù)據(jù)源跳夭,1個master涂圆,2兩個slave,1個路由數(shù)據(jù)源币叹。前3個數(shù)據(jù)源都是為了生成第4個數(shù)據(jù)源润歉,而且后續(xù)我們只用這最后一個路由數(shù)據(jù)源。
MyBatis配置
@Configuration
public class MyBatisConfig {
@Resource(name = "myRoutingDataSource")
private DataSource myRoutingDataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(myRoutingDataSource);
}
}
由于Spring容器中現(xiàn)在有4個數(shù)據(jù)源颈抚,所以我們需要為事務(wù)管理器和MyBatis手動指定一個明確的數(shù)據(jù)源踩衩。
3.3. 設(shè)置路由key / 查找數(shù)據(jù)源
目標數(shù)據(jù)源就是那前3個這個我們是知道的,但是使用的時候是如果查找數(shù)據(jù)源的呢?
首先驱富,我們定義一個枚舉來代表這三個數(shù)據(jù)源
package com.cjs.example.enums;
public enum DBTypeEnum {
MASTER, SLAVE1, SLAVE2;
}
接下來锚赤,通過ThreadLocal將數(shù)據(jù)源設(shè)置到每個線程上下文中
public class DBContextHolder {
private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
private static final AtomicInteger counter = new AtomicInteger(-1);
public static void set(DBTypeEnum dbType) {
contextHolder.set(dbType);
}
public static DBTypeEnum get() {
return contextHolder.get();
}
public static void master() {
set(DBTypeEnum.MASTER);
System.out.println("切換到master");
}
public static void slave() {
// 輪詢
int index = counter.getAndIncrement() % 2;
if (counter.get() > 9999) {
counter.set(-1);
}
if (index == 0) {
set(DBTypeEnum.SLAVE1);
System.out.println("切換到slave1");
}else {
set(DBTypeEnum.SLAVE2);
System.out.println("切換到slave2");
}
}
}
獲取路由key
public class MyRoutingDataSource extends AbstractRoutingDataSource {
@Nullable
@Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.get();
}
}
設(shè)置路由key
默認情況下,所有的查詢都走從庫褐鸥,插入/修改/刪除走主庫线脚。我們通過方法名來區(qū)分操作類型(CRUD)
@Aspect
@Component
public class DataSourceAop {
@Pointcut("!@annotation(com.cjs.example.annotation.Master) " +
"&& (execution(* com.cjs.example.service..*.select*(..)) " +
"|| execution(* com.cjs.example.service..*.get*(..)))")
public void readPointcut() {
}
@Pointcut("@annotation(com.cjs.example.annotation.Master) " +
"|| execution(* com.cjs.example.service..*.insert*(..)) " +
"|| execution(* com.cjs.example.service..*.add*(..)) " +
"|| execution(* com.cjs.example.service..*.update*(..)) " +
"|| execution(* com.cjs.example.service..*.edit*(..)) " +
"|| execution(* com.cjs.example.service..*.delete*(..)) " +
"|| execution(* com.cjs.example.service..*.remove*(..))")
public void writePointcut() {
}
@Before("readPointcut()")
public void read() {
DBContextHolder.slave();
}
@Before("writePointcut()")
public void write() {
DBContextHolder.master();
}
/**
* 另一種寫法:if...else... 判斷哪些需要讀從數(shù)據(jù)庫,其余的走主數(shù)據(jù)庫
*/
// @Before("execution(* com.cjs.example.service.impl.*.*(..))")
// public void before(JoinPoint jp) {
// String methodName = jp.getSignature().getName();
//
// if (StringUtils.startsWithAny(methodName, "get", "select", "find")) {
// DBContextHolder.slave();
// }else {
// DBContextHolder.master();
// }
// }
}
有一般情況就有特殊情況叫榕,特殊情況是某些情況下我們需要強制讀主庫浑侥,針對這種情況,我們定義一個主鍵晰绎,用該注解標注的就讀主庫
package com.cjs.example.annotation;
public @interface Master {
}
例如寓落,假設(shè)我們有一張表member
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
private MemberMapper memberMapper;
@Transactional
@Override
public int insert(Member member) {
return memberMapper.insert(member);
}
@Master
@Override
public int save(Member member) {
return memberMapper.insert(member);
}
@Override
public List<Member> selectAll() {
return memberMapper.selectByExample(new MemberExample());
}
@Master
@Override
public String getToken(String appId) {
// 有些讀操作必須讀主數(shù)據(jù)庫
// 比如,獲取微信access_token寒匙,因為高峰時期主從同步可能延遲
// 這種情況下就必須強制從主數(shù)據(jù)讀
return null;
}
}