因为公司业务原因,有多市场多数据源。所以常用方法是上层抽象,下层注入:
数据库: mongodb
但是因为api层传递的countryCode是不一样的,所以通过一个一个注入方式然后equals判断选择哪个还是太low了。
想了一种方法,没次在使用的时候进行setCountryCode,但是具体还没测试。 后续更新。。。
/**
* @author hope 2022年03月04日 上午10:22:46
*/
@Service
public class ExecuteOrderRealDao extends AbstractExecuteOrderHisDao {
public static volatile String tableName = StringUtils.EMPTY;
public ExecuteOrderRealDao() {
super(tableName);
}
public static void setCountryCode(String countryCode) {
ExecuteOrderRealDao.tableName = ExecOrderTable.getTableName(countryCode);
}
public static void setTableName(String tableName) {
ExecuteOrderRealDao.tableName = tableName;
}
@Getter
@AllArgsConstructor
public enum ExecOrderTable {
US("US", "polaroid_country_us_primary_t_execute_order"),
HK("HK", "polaroid_country_hk_primary_t_execute_order"),
SG("SG", "polaroid_country_sg_primary_t_execute_order"),
ACCOUNT("ACCOUNT", "polaroid_account_primary_test_t_execute_order");
private String countryCode;
private String tableName;
/**
* 默认返回账户表
*/
public static String getTableName(String countryCode) {
for (ExecuteOrderRealDao.ExecOrderTable value : values()) {
if (value.getCountryCode().equals(countryCode)) {
return value.getTableName();
}
}
return ExecOrderTable.ACCOUNT.getTableName();
}
}
}
欢迎大佬评论,私聊。
更新: 目前最好的方式通过转map来达到多数据源注入方式
具体代码如下:
/**
* @author hope 2022年03月09日 上午10:29:00
*/
@Slf4j
@Service
public class EquityProfitLossHistoryService {
@Autowired
private List<EquityProfitLossHistoryDao> daoList;
private Map<String, EquityProfitLossHistoryDao> daoMap;
@PostConstruct
public void init() {
daoMap = daoList.stream().collect(Collectors.toMap(EquityProfitLossHistoryDao::countryCode, Function.identity()));
}
/**
* 默认获取市场级别(account)
*
* @param countryCode
* @return
*/
public EquityProfitLossHistoryDao get(String countryCode) {
return daoMap.get(Optional.ofNullable(countryCode).orElse(Constant.ACCOUNT));
}
}
- [ 萱儿AXW ]