之前写过一篇BeetlSQL3+多租户的实现方案,传送门:https://segmentfault.com/a/11...
现做一下补充以及完善
1:初始化动态数据源时直接构建SQLManager,这样通过工具类获取时就不用每次都构建了.
for (Tenant dto : tenantList) {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(dto.getDbDriver());
dataSource.setJdbcUrl(dto.getDbUrl());
dataSource.setUsername(dto.getDbUsername());
dataSource.setPassword(dto.getDbPassword());
dataSource.setDataSourceProperties(master.getDataSourceProperties());
dataSourceMap.put(dto.getTenantId(), dataSource);
//构建SQLManager 将所有数据源注册进 SQLManagerBuilder.sqlManagerMap
ConnectionSource source = ConnectionSourceHelper.getSingle(dataSource);
SQLManagerBuilder builder = new SQLManagerBuilder(source);
builder.setNc(new UnderlinedNameConversion());
builder.setInters(new Interceptor[] { new SqlDebugInterceptor() });
builder.setDbStyle(new MySqlStyle());
builder.setName(dto.getTenantId());
builder.build();
}
//设置数据源
dynamicDataSource.setDataSources(dataSourceMap);
//执行生效
dynamicDataSource.afterPropertiesSet();
//获取SQLManager对象
SQLManagerBuilder.sqlManagerMap.get(key);
2:对service方法进行切面,手动管理事务
@Component
@Aspect
@Order(-1)
public class DSTransactionManagerAspect {
private static final Logger log = LoggerFactory.getLogger(DSTransactionManagerAspect.class);
@Pointcut("execution(* com.test.service..*.*(..))")
public void dataSourceSwitchPointCut() {
}
@Around(value = "@annotation(org.springframework.transaction.annotation.Transactional)")
public Object handler(
ProceedingJoinPoint point) throws Throwable {
Object proceed = null;
try {
//开启事务
DSTransactionManager.start();
proceed = point.proceed();
//提交事务
DSTransactionManager.commit();
}
catch (Exception e) {
//回滚事务
log.error(e.toString());
DSTransactionManager.rollback();
throw new Exception(e);
}
finally {
//清空
DSTransactionManager.clear();
}
return proceed;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。