主从库双数据源

This commit is contained in:
zc
2026-05-07 15:58:13 +08:00
parent 3113ba2542
commit 470a2dbe6e
17 changed files with 374 additions and 33 deletions

View File

@@ -0,0 +1,18 @@
package top.wms.admin.common.config.mybatis;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import top.wms.admin.common.constant.DataSourceContextHolder;
/**
* 动态数据源路由
*
* @author Admin
* @since 2024/12/22
*/
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}

View File

@@ -0,0 +1,40 @@
package top.wms.admin.common.constant;
/**
* 数据源上下文 Holder
*
* @author Admin
* @since 2024/12/22
*/
public class DataSourceContextHolder {
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
private DataSourceContextHolder() {
}
/**
* 设置数据源
*
* @param dataSource 数据源标识
*/
public static void setDataSource(String dataSource) {
CONTEXT_HOLDER.set(dataSource);
}
/**
* 获取数据源
*
* @return 数据源标识
*/
public static String getDataSource() {
return CONTEXT_HOLDER.get();
}
/**
* 清除数据源
*/
public static void clearDataSource() {
CONTEXT_HOLDER.remove();
}
}

View File

@@ -74,6 +74,11 @@ public class UserContext implements Serializable {
*/
private String clientId;
/**
* 数据源标识
*/
private String dataSource;
public UserContext(Set<String> permissions, Set<RoleContext> roles, Integer passwordExpirationDays) {
this.permissions = permissions;
this.setRoles(roles);
@@ -113,4 +118,4 @@ public class UserContext implements Serializable {
}
return this.pwdResetTime.plusDays(this.passwordExpirationDays).isBefore(LocalDateTime.now());
}
}
}

View File

@@ -0,0 +1,30 @@
package top.wms.admin.common.enums;
/**
* 数据源枚举
*
* @author Admin
* @since 2024/12/22
*/
public enum DataSourceEnum {
/**
* 主数据源
*/
WMS("wms"),
/**
* 从数据源
*/
WMS2("wms2");
private final String value;
DataSourceEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}