项目源码地址 https://github.com/HuangPugang/Java-lean
- multidata 读写分离实现部分
- multidata-test 测试项目
导读
本文就springboot+mybatis实现数据库一写多读方案的一些探讨。实现数据库的方案有很多,可以从代码层实现,也可以使用中间件进行实现。
常见的中间件有Mycat、Atlas等,
而我们今天讨论的是简易的代码层通过多数据源实现。
思路
我们在使用springboot+mybatis的时候,会再application.yml中配置一个数据源,配置完之后我们就知道操作mapper的时候就会连接配置好的数据库地址。
现在通过配置多个数据源+重写AbstractRoutingDataSource数据源路由+注解 来实现一写多读的实现
代码实现
DSProperties.java
配置文件,用于读取配置文件的属性
DSType.java
数据源类型,区分读or写
public enum DSType {
read("read", "从库"),
write("write", "主库");
}
DSTypeThreadLocal.java
数据源类型本地变量,使用ThreadLocal保存读库还是写库的类型,保证同一线程下访问同一张表
public class DSTypeThreadLocal {
private static Logger log = LoggerFactory.getLogger(DSTypeThreadLocal.class);
//线程本地环境
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属性封装工具类
RoutingDS.java
数据源路由,在这个类中决定我们所要访问的数据源
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();
}
//读库, 简单负载均衡
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());
//设置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("请先配置写数据库");
}
System.err.println("初始化写数据源");
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("请先配置读数据库");
}
System.err.println("初始化读数据源");
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");
//初始化读数据源
initReadDataSource();
//初始化写数据源
initWriteDataSource();
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put(DSType.write.getType(), writeSource);
if (readSourceList == null && readSourceList.size() == 0) {
throw new RuntimeException("请配置读数据库");
}
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();
//路由类,寻找对应的数据源
AbstractRoutingDataSource proxy = new RoutingDS(readSize);
proxy.setDefaultTargetDataSource(writeSource);//默认库
proxy.setTargetDataSources(targetDataSources);
return proxy;
}
@Bean
@DependsOn("sqlSessionFactory")
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
//事务管理
@Bean
public PlatformTransactionManager annotationDriveTransactionManager() {
System.out.println("事务管理");
return new DataSourceTransactionManager((DataSource) SpringContext.getBean("roundRobinDataSourceProxy"));
}
}
注解类
@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 {
}
切面实现
对于数据源选择我们通过三种方式来决定读还是写
- 拦截service方法
拦截service方法只是简单通过方法名来确定是否是读写,通常读数据库为list select 开头,而写通常为add、insert、update、delete开头,优先级最低 - 拦截自定义注解
通过自定义注解来显示指定读库还是写库 - 拦截事务注解
如果有有事务,那必定是访问写库,优先级最高
具体代码可参考项目源码。通过写此项目,可以加深对springboot、mybatis数据访问的理解。