Browse Source

fix数据源切换

LLL 1 year ago
parent
commit
47f4038aa7

+ 80 - 0
module_kzks/src/main/java/org/jeecg/modules/dataSourceSwitch/manage/DataSourceManagement.java

@@ -0,0 +1,80 @@
+package org.jeecg.modules.dataSourceSwitch.manage;
+
+import org.jeecg.modules.dataSourceSwitch.enums.DataSourceType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Primary;
+import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import javax.sql.DataSource;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Primary
+@Component
+public class DataSourceManagement extends AbstractRoutingDataSource {
+
+    @Resource
+    private DataSource master;
+
+    @Resource
+    private DataSource slave;
+
+    public static final Logger log = LoggerFactory.getLogger(DataSourceManagement.class);
+
+    /**
+     * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
+     * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
+     */
+    public static final ThreadLocal<String> flag = new ThreadLocal<>();
+
+    /**
+     * 设置数据源的变量
+     */
+    public static void setDataSourceType(String dsType)
+    {
+        log.info("切换到{}数据源", dsType);
+        flag.set(dsType);
+    }
+
+    /**
+     * 获得数据源的变量
+     */
+    public static String getDataSourceType()
+    {
+        return flag.get();
+    }
+
+    /**
+     * 清空数据源变量
+     */
+    public static void clearDataSourceType()
+    {
+        flag.remove();
+    }
+
+
+
+    public DataSourceManagement(){
+        flag.set(DataSourceType.MASTER.name());
+    }
+
+    @Override
+    protected Object determineCurrentLookupKey() {
+        return flag.get();
+    }
+
+    @Override
+    public void afterPropertiesSet() {
+        Map<Object,Object> targetDataSource = new ConcurrentHashMap<>();
+        targetDataSource.put(DataSourceType.MASTER.name(),master);
+        targetDataSource.put(DataSourceType.SLAVE.name(),slave);
+        super.setTargetDataSources(targetDataSource);
+        super.setDefaultTargetDataSource(master);
+        super.afterPropertiesSet();
+    }
+
+
+}