Java中MybatisPlus使用多線程多數據源失效
文章目錄
- Java中MybatisPlus使用多線程多數據源失效
- 一:背景
- 二:解決方法
- 三:其他導致@DS失效的條件
- 3.1、@Transactional
一:背景
Mybatis-Plus
使用異步任務后不能找到指定設置的@DS數據庫,所有請求指向了主數據庫
二:解決方法
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
public void saveInventoryFlow(Long orgKkd, String orgNameKkd, List<SaveAbInventoryFlowReq> requests) {if (ObjectUtil.isEmpty(requests)) {return;}CompletableFuture.runAsync(() -> {DynamicDataSourceContextHolder.push("qjs");List<TemInventoryFlow> list = requests.stream().map(request -> {TemInventoryFlow abInventoryFlow = new TemInventoryFlow();BeanUtils.copyProperties(request, abInventoryFlow);abInventoryFlow.setOrgId(orgKkd);return abInventoryFlow;}).collect(Collectors.toList());temInventoryFlowRepo.saveBatch(list);DynamicDataSourceContextHolder.clear();}, poolExecutor);
}
三:其他導致@DS失效的條件
3.1、@Transactional
Spring的@Transactional聲明式事務管理時通過動態代理實現的。
解決方法:
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)