共计 1700 个字符,预计需要花费 5 分钟才能阅读完成。
之前写过一篇 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; | |
} | |
} |
正文完