項(xiàng)目源碼地址 https://github.com/HuangPugang/Java-lean
- multidata 讀寫(xiě)分離實(shí)現(xiàn)部分
- multidata-test 測(cè)試項(xiàng)目
導(dǎo)讀
本文就springboot+mybatis實(shí)現(xiàn)數(shù)據(jù)庫(kù)一寫(xiě)多讀方案的一些探討断部。實(shí)現(xiàn)數(shù)據(jù)庫(kù)的方案有很多硝训,可以從代碼層實(shí)現(xiàn)版确,也可以使用中間件進(jìn)行實(shí)現(xiàn)。
常見(jiàn)的中間件有Mycat、Atlas等恼五,
而我們今天討論的是簡(jiǎn)易的代碼層通過(guò)多數(shù)據(jù)源實(shí)現(xiàn)。
思路
我們?cè)谑褂胹pringboot+mybatis的時(shí)候,會(huì)再application.yml中配置一個(gè)數(shù)據(jù)源芬位,配置完之后我們就知道操作mapper的時(shí)候就會(huì)連接配置好的數(shù)據(jù)庫(kù)地址。
現(xiàn)在通過(guò)配置多個(gè)數(shù)據(jù)源+重寫(xiě)AbstractRoutingDataSource數(shù)據(jù)源路由+注解 來(lái)實(shí)現(xiàn)一寫(xiě)多讀的實(shí)現(xiàn)
代碼實(shí)現(xiàn)
DSProperties.java
配置文件带到,用于讀取配置文件的屬性
DSType.java
數(shù)據(jù)源類(lèi)型昧碉,區(qū)分讀or寫(xiě)
public enum DSType {
read("read", "從庫(kù)"),
write("write", "主庫(kù)");
}
DSTypeThreadLocal.java
數(shù)據(jù)源類(lèi)型本地變量,使用ThreadLocal保存讀庫(kù)還是寫(xiě)庫(kù)的類(lèi)型,保證同一線程下訪問(wèn)同一張表
public class DSTypeThreadLocal {
private static Logger log = LoggerFactory.getLogger(DSTypeThreadLocal.class);
//線程本地環(huán)境
private static final ThreadLocal<String> dsType = new ThreadLocal<String>();
public static ThreadLocal<String> getLocal() {
return dsType;
}
public static void setRead() {
dsType.set(DSType.read.getType());
}
public static void setWrite() {
dsType.set(DSType.write.getType());
}
public static String getCurrentType() {
if (StringUtils.isEmpty(dsType.get())) {
return DSType.read.getType();
}
return dsType.get();
}
public static void clear() {
dsType.remove();
}
}
DBHelper.java
DB屬性封裝工具類(lèi)
RoutingDS.java
數(shù)據(jù)源路由被饿,在這個(gè)類(lèi)中決定我們所要訪問(wèn)的數(shù)據(jù)源
public class RoutingDS extends AbstractRoutingDataSource {
AtomicInteger count = new AtomicInteger(0);
private Integer readSize;
public RoutingDS(Integer readSize) {
this.readSize = readSize;
}
@Override
protected Object determineCurrentLookupKey() {
String typeKey = DSTypeThreadLocal.getCurrentType();
if (typeKey == null) {
return DSType.write.getType();
}
if (typeKey.equals(DSType.write.getType())) {
return DSType.write.getType();
}
//讀庫(kù)四康, 簡(jiǎn)單負(fù)載均衡
int number = count.getAndAdd(1);
int lookupKey = number % readSize;
return DSType.read.getType() + lookupKey;
}
}
MybatisConfig.java
配置mybatis一些配置文件
@Configuration
@AutoConfigureAfter(DSProperties.class)
public class MybatisConfig {
private static Logger log = LoggerFactory.getLogger(MybatisConfig.class);
@Autowired
DSProperties dp;
private DataSource writeSource;
private List<DataSource> readSourceList;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
try {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(roundRobinDataSourceProxy());
//設(shè)置mapper.xml文件所在位置
Resource[] resources = new PathMatchingResourcePatternResolver().getResources(dp.getMapperLocations());
sessionFactoryBean.setMapperLocations(resources);
return sessionFactoryBean.getObject();
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
}
private void initWriteDataSource() {
if (dp.getWrite() == null) {
throw new RuntimeException("請(qǐng)先配置寫(xiě)數(shù)據(jù)庫(kù)");
}
System.err.println("初始化寫(xiě)數(shù)據(jù)源");
PoolProperties p = DBHelper.buildPoolProperties(dp.getWrite());
p.setLogAbandoned(true);
p.setDefaultAutoCommit(true);
writeSource = new org.apache.tomcat.jdbc.pool.DataSource(p) {
@PreDestroy
public void close() {
super.close(true);
}
};
}
private void initReadDataSource() {
readSourceList = new ArrayList<>();
if (dp.getReads() == null || dp.getReads().size() == 0) {
throw new RuntimeException("請(qǐng)先配置讀數(shù)據(jù)庫(kù)");
}
System.err.println("初始化讀數(shù)據(jù)源");
for (int i = 0; i < dp.getReads().size(); i++) {
PoolProperties p = DBHelper.buildPoolProperties(dp.getReads().get(i));
p.setLogAbandoned(true);
p.setDefaultAutoCommit(true);
readSourceList.add(new org.apache.tomcat.jdbc.pool.DataSource(p) {
@PreDestroy
public void close() {
super.close(true);
}
});
}
}
@Bean(name = "roundRobinDataSourceProxy")
public AbstractRoutingDataSource roundRobinDataSourceProxy() {
System.err.println("roundRobinDataSourceProxy");
//初始化讀數(shù)據(jù)源
initReadDataSource();
//初始化寫(xiě)數(shù)據(jù)源
initWriteDataSource();
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put(DSType.write.getType(), writeSource);
if (readSourceList == null && readSourceList.size() == 0) {
throw new RuntimeException("請(qǐng)配置讀數(shù)據(jù)庫(kù)");
}
for (int i = 0; i < readSourceList.size(); i++) {
System.err.println("targetDataSources=" + DSType.read.getType() + i);
targetDataSources.put(DSType.read.getType() + i, readSourceList.get(i));
}
final int readSize = readSourceList.size();
//路由類(lèi),尋找對(duì)應(yīng)的數(shù)據(jù)源
AbstractRoutingDataSource proxy = new RoutingDS(readSize);
proxy.setDefaultTargetDataSource(writeSource);//默認(rèn)庫(kù)
proxy.setTargetDataSources(targetDataSources);
return proxy;
}
@Bean
@DependsOn("sqlSessionFactory")
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
//事務(wù)管理
@Bean
public PlatformTransactionManager annotationDriveTransactionManager() {
System.out.println("事務(wù)管理");
return new DataSourceTransactionManager((DataSource) SpringContext.getBean("roundRobinDataSourceProxy"));
}
}
注解類(lèi)
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DSRead {
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface DSWrite {
}
切面實(shí)現(xiàn)
對(duì)于數(shù)據(jù)源選擇我們通過(guò)三種方式來(lái)決定讀還是寫(xiě)
- 攔截service方法
攔截service方法只是簡(jiǎn)單通過(guò)方法名來(lái)確定是否是讀寫(xiě)狭握,通常讀數(shù)據(jù)庫(kù)為list select 開(kāi)頭闪金,而寫(xiě)通常為add、insert论颅、update哎垦、delete開(kāi)頭,優(yōu)先級(jí)最低 - 攔截自定義注解
通過(guò)自定義注解來(lái)顯示指定讀庫(kù)還是寫(xiě)庫(kù) - 攔截事務(wù)注解
如果有有事務(wù)恃疯,那必定是訪問(wèn)寫(xiě)庫(kù)漏设,優(yōu)先級(jí)最高
具體代碼可參考項(xiàng)目源碼。通過(guò)寫(xiě)此項(xiàng)目今妄,可以加深對(duì)springboot愿题、mybatis數(shù)據(jù)訪問(wèn)的理解。