From eca1c2ce8506dfd5ad8f94235382b666ea831dfd Mon Sep 17 00:00:00 2001
From: zhaowenxuan <chacca165@163.com>
Date: 星期六, 08 二月 2025 17:58:19 +0800
Subject: [PATCH] 动态切换数据库实现

---
 ltkj-hosp/src/main/java/com/ltkj/db/DataSourceConfig.java                                      |  247 ++++++++++++++++++++++++++++++
 ltkj-admin/src/main/java/com/ltkj/web/controller/system/SysRoleController.java                 |   77 +++++++++
 ltkj-framework/src/main/java/com/ltkj/framework/aspectj/DataSourceAspect.java                  |    5 
 ltkj-hosp/src/main/java/com/ltkj/db/HospDynamicDataSource.java                                 |   14 +
 ltkj-framework/src/main/java/com/ltkj/framework/interceptor/DBChangeInterceptor.java           |   10 
 ltkj-hosp/pom.xml                                                                              |   17 ++
 ltkj-hosp/src/main/java/com/ltkj/db/DruidProperties.java                                       |   61 +++++++
 ltkj-framework/src/main/java/com/ltkj/framework/datasource/DynamicDataSourceContextHolder.java |   10 
 pom.xml                                                                                        |   12 +
 ltkj-framework/src/main/java/com/ltkj/framework/config/DruidConfig.java                        |   20 +-
 ltkj-framework/src/main/java/com/ltkj/framework/config/WebConfig.java                          |    3 
 11 files changed, 447 insertions(+), 29 deletions(-)

diff --git a/ltkj-admin/src/main/java/com/ltkj/web/controller/system/SysRoleController.java b/ltkj-admin/src/main/java/com/ltkj/web/controller/system/SysRoleController.java
index 7d4215e..19ea624 100644
--- a/ltkj-admin/src/main/java/com/ltkj/web/controller/system/SysRoleController.java
+++ b/ltkj-admin/src/main/java/com/ltkj/web/controller/system/SysRoleController.java
@@ -1,10 +1,30 @@
 package com.ltkj.web.controller.system;
 
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import javax.servlet.http.HttpServletResponse;
 
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.core.util.RandomUtil;
+import com.ltkj.db.DataSourceConfig;
+import com.ltkj.db.DataSourceContextHolder;
+import com.ltkj.hosp.domain.DictHosp;
+import com.ltkj.hosp.service.IDictHospService;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.util.FileCopyUtils;
 import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
@@ -55,6 +75,13 @@
 
     @Autowired
     private ISysDeptService deptService;
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
+    @Autowired
+    private IDictHospService dictHospService;
+
+    @Value("${config.path}")
+    private String path;
 
 //    @PreAuthorize("@ss.hasPermi('system:role:list')")
     @GetMapping("/list")
@@ -245,4 +272,54 @@
         ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
         return ajax;
     }
+
+    @Autowired
+    private DataSourceConfig dataSourceConfig;
+
+    /**
+     * 浠庡簱鎵归噺鎵цsql
+     * 璇诲彇鏈湴sql鏂囦欢
+     * @return
+     */
+    @GetMapping("/execUpdateSql")
+    public AjaxResult execUpdateSql() {
+        DataSourceContextHolder.setDataSourceKey("default");
+        List<DictHosp> list = dictHospService.list();
+        List<Map<String, Object>> resultList = new ArrayList<>();
+        for (DictHosp dictHosp : list) {
+            String dbName = dictHosp.getDbname();
+            Map<String, Object> dbResult = new HashMap<>();
+            dbResult.put("database", dbName);
+            List<String> successList = new ArrayList<>();
+            List<String> errorList = new ArrayList<>();
+            try {
+                InputStreamReader reader = new InputStreamReader(Files.newInputStream(Paths.get(path + File.separator + "update.sql")), StandardCharsets.UTF_8);
+                String sqlContent = FileCopyUtils.copyToString(reader);
+                String[] sqlStatements = sqlContent.split("\\|-\\|");
+                for (String sql : sqlStatements) {
+                    sql = sql.trim();
+                    if (!sql.isEmpty()) {
+                        // INSERT INTO `api_config` (`id`, `api_url`, `api_method`, `tab_name`, `is_response`, `primary_keys`, `remark`, `result_code_key`, `result_data_key`, `type`) VALUES (${id}, '${dbName}', '${randowmStr}', '${randowmStr}', 1, 'ResultData', '1.pas 妫�鏌ョ敵璇蜂俊鎭綔搴�', 'ResultCode', 'ResultData', 'pacs');
+//                        sql = sql.replace("${dbName}",dbName).replace("${id}", IdUtil.getSnowflake().nextIdStr()).replace("${randowmStr}", RandomUtil.randomString(10));
+                        try {
+                            dataSourceConfig.addDataSource(dbName);
+                            DataSourceContextHolder.setDataSourceKey(dbName);
+                            jdbcTemplate.execute(sql);
+                            successList.add(sql);
+                        } catch (Exception e) {
+                            errorList.add(sql + " -> ERROR: " + e.getMessage());
+                        }
+                    }
+                }
+            } catch (IOException e) {
+                return AjaxResult.error("璇诲彇SQL鏂囦欢澶辫触锛�" + e.getMessage());
+            }
+            dbResult.put("successSQL", successList);
+            dbResult.put("failedSQL", errorList);
+            resultList.add(dbResult);
+        }
+        DataSourceContextHolder.clear();
+        return AjaxResult.success(resultList);
+    }
+
 }
diff --git a/ltkj-framework/src/main/java/com/ltkj/framework/aspectj/DataSourceAspect.java b/ltkj-framework/src/main/java/com/ltkj/framework/aspectj/DataSourceAspect.java
index 1dccc09..e0014fd 100644
--- a/ltkj-framework/src/main/java/com/ltkj/framework/aspectj/DataSourceAspect.java
+++ b/ltkj-framework/src/main/java/com/ltkj/framework/aspectj/DataSourceAspect.java
@@ -2,6 +2,7 @@
 
 import java.util.Objects;
 
+import com.ltkj.db.DataSourceContextHolder;
 import com.ltkj.framework.datasource.DynamicDataSourceContextHolder;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
@@ -38,14 +39,14 @@
         DataSource dataSource = getDataSource(point);
 
         if (StringUtils.isNotNull(dataSource)) {
-            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
+            DataSourceContextHolder.setDataSourceKey(dataSource.value().name());
         }
 
         try {
             return point.proceed();
         } finally {
             // 閿�姣佹暟鎹簮 鍦ㄦ墽琛屾柟娉曚箣鍚�
-            DynamicDataSourceContextHolder.clearDataSourceType();
+            DataSourceContextHolder.clear();
         }
     }
 
diff --git a/ltkj-framework/src/main/java/com/ltkj/framework/config/DruidConfig.java b/ltkj-framework/src/main/java/com/ltkj/framework/config/DruidConfig.java
index df79300..a7c2639 100644
--- a/ltkj-framework/src/main/java/com/ltkj/framework/config/DruidConfig.java
+++ b/ltkj-framework/src/main/java/com/ltkj/framework/config/DruidConfig.java
@@ -35,7 +35,7 @@
  *
  * @author ltkj
  */
-@Configuration
+//@Configuration
 @Slf4j
 public class DruidConfig {
 
@@ -69,7 +69,7 @@
     private String dbName;
 
 
-    @Bean
+//    @Bean
 //    @ConfigurationProperties("spring.datasource.druid.master")
     public DataSource masterDataSource(DruidProperties druidProperties) {
         DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
@@ -150,7 +150,7 @@
         return druidProperties.dataSource(dataSource);
     }
 
-    @Bean
+//    @Bean
 //    @ConfigurationProperties("spring.datasource.druid.slavehis")
 //    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavehis", name = "enabled", havingValue = "true")
     public DataSource slaveHisDataSource(DruidProperties druidProperties) {
@@ -193,7 +193,7 @@
         return druidProperties.dataSource(dataSource);
     }
 
-    @Bean
+//    @Bean
 //    @ConfigurationProperties("spring.datasource.druid.slavelis")
 //    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavelis", name = "enabled", havingValue = "true")
     public DataSource slaveDataLisSource(DruidProperties druidProperties) {
@@ -235,7 +235,7 @@
         return druidProperties.dataSource(dataSource);
     }
 
-    @Bean
+//    @Bean
 //    @ConfigurationProperties("spring.datasource.druid.slavepacs")
 //    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavepacs", name = "enabled", havingValue = "true")
     public DataSource slaveDataPacsSource(DruidProperties druidProperties) {
@@ -278,7 +278,7 @@
         return druidProperties.dataSource(dataSource);
     }
 
-    @Bean
+//    @Bean
 //    @ConfigurationProperties("spring.datasource.druid.slavepacs")
 //    @ConditionalOnProperty(prefix = "spring.datasource.druid.slavepacs", name = "enabled", havingValue = "true")
     public DataSource slaveDataWsSource(DruidProperties druidProperties) {
@@ -427,8 +427,8 @@
     }
 
 
-    @Bean(name = "dynamicDataSource")
-    @Primary
+//    @Bean(name = "dynamicDataSource")
+//    @Primary
     public DynamicDataSource dataSource(DataSource masterDataSource) {
         Map<Object, Object> targetDataSources = new HashMap<>();
         targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
@@ -458,8 +458,8 @@
      * 鍘婚櫎鐩戞帶椤甸潰搴曢儴鐨勫箍鍛�
      */
     @SuppressWarnings({"rawtypes", "unchecked"})
-    @Bean
-    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
+//    @Bean
+//    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
     public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
         // 鑾峰彇web鐩戞帶椤甸潰鐨勫弬鏁�
         DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
diff --git a/ltkj-framework/src/main/java/com/ltkj/framework/config/WebConfig.java b/ltkj-framework/src/main/java/com/ltkj/framework/config/WebConfig.java
index d8ca377..4ab71c6 100644
--- a/ltkj-framework/src/main/java/com/ltkj/framework/config/WebConfig.java
+++ b/ltkj-framework/src/main/java/com/ltkj/framework/config/WebConfig.java
@@ -38,7 +38,8 @@
                 .excludePathPatterns(new String[]{
                         "/system/dict/data/**",
                         "/system/dict/type/**",
-                        "/captchaImage","/getCaptchaConfigKey/**"
+                        "/captchaImage","/getCaptchaConfigKey/**",
+                        "/system/role/execUpdateSql"
 //                        ,
 //                        "/login", "/register", "/captchaImage","/cus/**","/getCaptchaConfigKey","/report/jmreport/**",
 //                        "/sqlserver/getdata/**","/api/His/**","/system/config/zx","/system/config/gxxmpym","/system/report/savePdf",
diff --git a/ltkj-framework/src/main/java/com/ltkj/framework/datasource/DynamicDataSourceContextHolder.java b/ltkj-framework/src/main/java/com/ltkj/framework/datasource/DynamicDataSourceContextHolder.java
index e64c1bc..52da622 100644
--- a/ltkj-framework/src/main/java/com/ltkj/framework/datasource/DynamicDataSourceContextHolder.java
+++ b/ltkj-framework/src/main/java/com/ltkj/framework/datasource/DynamicDataSourceContextHolder.java
@@ -1,5 +1,6 @@
 package com.ltkj.framework.datasource;
 
+import com.ltkj.db.DataSourceContextHolder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -22,20 +23,23 @@
      */
     public static void setDataSourceType(String dsType) {
         log.info("鍒囨崲鍒皗}鏁版嵁婧�", dsType);
-        CONTEXT_HOLDER.set(dsType);
+//        CONTEXT_HOLDER.set(dsType);
+        DataSourceContextHolder.setDataSourceKey(dsType);
     }
 
     /**
      * 鑾峰緱鏁版嵁婧愮殑鍙橀噺
      */
     public static String getDataSourceType() {
-        return CONTEXT_HOLDER.get();
+//        return CONTEXT_HOLDER.get();
+        return DataSourceContextHolder.getDataSourceKey();
     }
 
     /**
      * 娓呯┖鏁版嵁婧愬彉閲�
      */
     public static void clearDataSourceType() {
-        CONTEXT_HOLDER.remove();
+//        CONTEXT_HOLDER.remove();
+        DataSourceContextHolder.clear();
     }
 }
diff --git a/ltkj-framework/src/main/java/com/ltkj/framework/interceptor/DBChangeInterceptor.java b/ltkj-framework/src/main/java/com/ltkj/framework/interceptor/DBChangeInterceptor.java
index a049f69..083f6a3 100644
--- a/ltkj-framework/src/main/java/com/ltkj/framework/interceptor/DBChangeInterceptor.java
+++ b/ltkj-framework/src/main/java/com/ltkj/framework/interceptor/DBChangeInterceptor.java
@@ -29,10 +29,10 @@
 
     @Autowired
     private IDictHospService dictHospService;
-//    @Autowired
-//    private DataSourceConfig dataSourceConfig;
     @Autowired
-    private DruidConfig druidConfig;
+    private DataSourceConfig dataSourceConfig;
+//    @Autowired
+//    private DruidConfig druidConfig;
 
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
@@ -55,8 +55,8 @@
                 response.getWriter().write("{\"message\":\"401锛氭壘涓嶅埌闄㈠尯鏁版嵁\"}");
                 return false;
             }
-//            dataSourceConfig.addDataSource(hosp.getDbname());
-            druidConfig.addDataSource(hosp.getDbname());
+            dataSourceConfig.addDataSource(hosp.getDbname());
+//            druidConfig.addDataSource(hosp.getDbname());
             DataSourceContextHolder.setDataSourceKey(hosp.getDbname());
         } catch (IOException e) {
             return false;
diff --git a/ltkj-hosp/pom.xml b/ltkj-hosp/pom.xml
index 91dd988..3c38f0c 100644
--- a/ltkj-hosp/pom.xml
+++ b/ltkj-hosp/pom.xml
@@ -28,6 +28,12 @@
         <dependency>
             <groupId>com.ltkj</groupId>
             <artifactId>ltkj-common</artifactId>
+            <exclusions>
+                <exclusion>
+                    <groupId>com.alibaba</groupId>
+                    <artifactId>druid</artifactId>
+                </exclusion>
+            </exclusions>
         </dependency>
 
         <!-- 闆嗘垚绉湪鎶ヨ〃-->
@@ -35,6 +41,12 @@
             <groupId>org.jeecgframework.jimureport</groupId>
             <artifactId>jimureport-spring-boot-starter</artifactId>
             <version>1.5.4</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>com.alibaba</groupId>
+                    <artifactId>druid</artifactId>
+                </exclusion>
+            </exclusions>
         </dependency>
 
         <!-- 闃块噷鏁版嵁搴撹繛鎺ユ睜 -->
@@ -43,6 +55,11 @@
             <artifactId>druid-spring-boot-starter</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid</artifactId>
+        </dependency>
+
     </dependencies>
 
 </project>
diff --git a/ltkj-hosp/src/main/java/com/ltkj/db/DataSourceConfig.java b/ltkj-hosp/src/main/java/com/ltkj/db/DataSourceConfig.java
index 8d5d828..9a6983f 100644
--- a/ltkj-hosp/src/main/java/com/ltkj/db/DataSourceConfig.java
+++ b/ltkj-hosp/src/main/java/com/ltkj/db/DataSourceConfig.java
@@ -1,20 +1,23 @@
 package com.ltkj.db;
 
 import com.alibaba.druid.pool.DruidDataSource;
+import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
+import com.ltkj.common.enums.DataSourceType;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
 import javax.sql.DataSource;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
+import java.io.*;
+import java.sql.SQLException;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
 
-//@Configuration
+@Slf4j
+@Configuration
 public class DataSourceConfig {
 
     private static final String DEFAULT_DATA_SOURCE_KEY = "default"; // 涓诲簱鐨勬爣璇�
@@ -64,6 +67,13 @@
         // 鍒濆鍖栭粯璁ゆ暟鎹簮涓轰富搴�
         dynamicDataSource.addTargetDataSource(DEFAULT_DATA_SOURCE_KEY, createDataSource(url, primaryUsername, primaryPassword));
 
+        DruidProperties properties = new DruidProperties();
+        dynamicDataSource.addTargetDataSource(DataSourceType.MASTER.name(),masterDataSource(properties));
+        dynamicDataSource.addTargetDataSource(DataSourceType.SLAVE_HIS.name(),slaveHisDataSource(properties));
+        dynamicDataSource.addTargetDataSource(DataSourceType.SLAVE_LIS.name(),slaveDataLisSource(properties));
+        dynamicDataSource.addTargetDataSource(DataSourceType.SLAVE_PACS.name(),slaveDataPacsSource(properties));
+        dynamicDataSource.addTargetDataSource(DataSourceType.SLAVE_WS.name(),slaveDataWsSource(properties));
+
         dynamicDataSource.setDefaultTargetDataSource(dynamicDataSource.getTargetDataSources().get(DEFAULT_DATA_SOURCE_KEY)); // 璁剧疆榛樿鏁版嵁婧�
         return dynamicDataSource;
     }
@@ -104,4 +114,233 @@
             }
         }
     }
+
+    private DataSource masterDataSource(DruidProperties druidProperties) {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties props = new Properties();
+        try {
+            // 浠庢枃浠朵腑璇诲彇閰嶇疆淇℃伅
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(url);
+            } catch (FileNotFoundException e) {
+                log.info("鏁版嵁搴撹繛鎺ユ枃浠舵壘涓嶅埌锛�");
+            }
+            props.load(fis);
+            fis.close();
+            // 鑾峰彇灞炴�у�煎苟璧嬪��
+            String hisenabled = props.getProperty("hisenabled");
+            if (hisenabled.equals("false"))
+                return null;
+            dataSource = creatMysql(hisenabled, props.getProperty("ip"),props.getProperty("prot"),props.getProperty("name"),props.getProperty("username"),props.getProperty("password"));
+            log.info("his鏁版嵁搴撹繛鎺ユ垚鍔�!!!");
+        } catch (Exception e) {
+            log.info("鏁版嵁搴撹繛鎺ュけ璐�  璇疯仈绯荤鐞嗗憳锛�");
+            e.printStackTrace();
+        }
+        return druidProperties.dataSource(dataSource);
+    }
+
+    private DataSource slaveHisDataSource(DruidProperties druidProperties) {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties props = new Properties();
+        try {
+            // 浠庢枃浠朵腑璇诲彇閰嶇疆淇℃伅
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(url);
+            } catch (FileNotFoundException e) {
+                log.info("鏁版嵁搴撹繛鎺ユ枃浠舵壘涓嶅埌锛�");
+            }
+            props.load(fis);
+            fis.close();
+            // 鑾峰彇灞炴�у�煎苟璧嬪��
+            String hisenabled = props.getProperty("hisenabled");
+            if (hisenabled.equals("false"))
+                return null;
+            String hisdbtype = props.getProperty("hisdbtype");
+            switch (hisdbtype){
+                case "sqlserver":
+                    dataSource = creatSqlServer(hisenabled, props.getProperty("hisip"),props.getProperty("hisprot"),props.getProperty("hisname"),props.getProperty("hisusername"),props.getProperty("hispassword"));
+                    break;
+                case "mysql":
+                    dataSource = creatMysql(hisenabled, props.getProperty("hisip"),props.getProperty("hisprot"),props.getProperty("hisname"),props.getProperty("hisusername"),props.getProperty("hispassword"));
+                    break;
+                case "oracle":
+                    dataSource = creatOracle(hisenabled, props.getProperty("hisip"),props.getProperty("hisprot"),props.getProperty("hisname"),props.getProperty("hisusername"),props.getProperty("hispassword"));
+                    break;
+                default:
+                    dataSource = creatSqlServer(hisenabled, props.getProperty("hisip"),props.getProperty("hisprot"),props.getProperty("hisname"),props.getProperty("hisusername"),props.getProperty("hispassword"));
+                    break;
+            }
+            log.info("his鏁版嵁搴撹繛鎺ユ垚鍔�!!!");
+        } catch (Exception e) {
+            log.info("鏁版嵁搴撹繛鎺ュけ璐�  璇疯仈绯荤鐞嗗憳锛�");
+            e.printStackTrace();
+        }
+        return druidProperties.dataSource(dataSource);
+    }
+
+    private DataSource slaveDataLisSource(DruidProperties druidProperties) {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties props = new Properties();
+        try {
+            // 浠庢枃浠朵腑璇诲彇閰嶇疆淇℃伅
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(url);
+            } catch (FileNotFoundException e) {
+                log.info("鏁版嵁搴撹繛鎺ユ枃浠舵壘涓嶅埌锛�");
+            }
+            props.load(fis);
+            fis.close();
+            String lisenabled = props.getProperty("lisenabled");
+            if (lisenabled.equals("false"))
+                return null;
+            String lisdbtype = props.getProperty("lisdbtype");
+            switch (lisdbtype){
+                case "sqlserver":
+                    dataSource = creatSqlServer(lisenabled, props.getProperty("lisip"),props.getProperty("lisprot"),props.getProperty("lisname"),props.getProperty("lisusername"),props.getProperty("lispassword"));
+                    break;
+                case "mysql":
+                    dataSource = creatMysql(lisenabled, props.getProperty("lisip"),props.getProperty("lisprot"),props.getProperty("lisname"),props.getProperty("lisusername"),props.getProperty("lispassword"));
+                    break;
+                case "oracle":
+                    dataSource = creatOracle(lisenabled, props.getProperty("lisip"),props.getProperty("lisprot"),props.getProperty("lisname"),props.getProperty("lisusername"),props.getProperty("lispassword"));
+                    break;
+                default:
+                    dataSource = creatMysql(lisenabled, props.getProperty("lisip"),props.getProperty("lisprot"),props.getProperty("lisname"),props.getProperty("lisusername"),props.getProperty("lispassword"));
+                    break;
+            }
+            log.info("Lis鏁版嵁搴撹繛鎺ユ垚鍔�!!!");
+        } catch (Exception e) {
+            log.info("鏁版嵁搴撹繛鎺ュけ璐�  璇疯仈绯荤鐞嗗憳锛�");
+            e.printStackTrace();
+        }
+        return druidProperties.dataSource(dataSource);
+    }
+
+    private DataSource slaveDataPacsSource(DruidProperties druidProperties) {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties props = new Properties();
+        try {
+            // 浠庢枃浠朵腑璇诲彇閰嶇疆淇℃伅
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(url);
+            } catch (FileNotFoundException e) {
+                log.info("鏁版嵁搴撹繛鎺ユ枃浠舵壘涓嶅埌");
+            }
+            props.load(fis);
+            fis.close();
+            // 杩欓噷鏄祴璇曞啓娉曪紝鍏蜂綋鐨剉alue鍙互閫氳繃璇锋眰鍙傛暟浼犻�掕繃鏉�
+            String pacsenabled = props.getProperty("pacsenabled");
+            if (pacsenabled.equals("false"))
+                return null;
+            String pacsdbtype = props.getProperty("pacsdbtype");
+            switch (pacsdbtype){
+                case "sqlserver":
+                    dataSource = creatSqlServer(pacsenabled, props.getProperty("pacsip"),props.getProperty("pacsprot"),props.getProperty("pacsname"),props.getProperty("pacsusername"),props.getProperty("pacspassword"));
+                    break;
+                case "mysql":
+                    dataSource = creatMysql(pacsenabled, props.getProperty("pacsip"),props.getProperty("pacsprot"),props.getProperty("pacsname"),props.getProperty("pacsusername"),props.getProperty("pacspassword"));
+                    break;
+                case "oracle":
+                    dataSource = creatOracle(pacsenabled, props.getProperty("pacsip"),props.getProperty("pacsprot"),props.getProperty("pacsname"),props.getProperty("pacsusername"),props.getProperty("pacspassword"));
+                    break;
+                default:
+                    dataSource = creatOracle(pacsenabled, props.getProperty("pacsip"),props.getProperty("pacsprot"),props.getProperty("pacsname"),props.getProperty("pacsusername"),props.getProperty("pacspassword"));
+                    break;
+            }
+            log.info("鏁版嵁搴撹繛鎺ユ垚鍔�!!!");
+        } catch (Exception e) {
+            log.info("鏁版嵁搴撹繛鎺ュけ璐�  璇疯仈绯荤鐞嗗憳锛�");
+            e.printStackTrace();
+        }
+        return druidProperties.dataSource(dataSource);
+    }
+
+    private DataSource slaveDataWsSource(DruidProperties druidProperties) {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties props = new Properties();
+        try {
+            // 浠庢枃浠朵腑璇诲彇閰嶇疆淇℃伅
+            FileInputStream fis = null;
+            try {
+                fis = new FileInputStream(url);
+            } catch (FileNotFoundException e) {
+                log.info("鏁版嵁搴撹繛鎺ユ枃浠舵壘涓嶅埌");
+            }
+            props.load(fis);
+            fis.close();
+            // 杩欓噷鏄祴璇曞啓娉曪紝鍏蜂綋鐨剉alue鍙互閫氳繃璇锋眰鍙傛暟浼犻�掕繃鏉�
+            String pacsenabled = props.getProperty("wsenabled");
+            if (pacsenabled.equals("false"))
+                return null;
+            String pacsdbtype = props.getProperty("wsdbtype");
+            switch (pacsdbtype){
+                case "sqlserver":
+                    dataSource = creatSqlServer(pacsenabled, props.getProperty("wsip"),props.getProperty("wsprot"),
+                            props.getProperty("wsname"),props.getProperty("wsusername"),props.getProperty("wspassword"));
+                    break;
+                case "mysql":
+                    dataSource = creatMysql(pacsenabled, props.getProperty("wsip"),
+                            props.getProperty("wsprot"),props.getProperty("wsname"),props.getProperty("wsusername"),props.getProperty("wspassword"));
+                    break;
+                case "oracle":
+                    dataSource = creatOracle(pacsenabled, props.getProperty("wsip"),
+                            props.getProperty("wsprot"),props.getProperty("wsname"),props.getProperty("wsusername"),props.getProperty("wspassword"));
+                    break;
+                default:
+                    dataSource = creatOracle(pacsenabled, props.getProperty("wsip"),props.getProperty("wsprot"),props.getProperty("wsname"),props.getProperty("wsusername")
+                            ,props.getProperty("wspassword"));
+                    break;
+            }
+            log.info("鏁版嵁搴撹繛鎺ユ垚鍔�!!!");
+        } catch (Exception e) {
+            log.info("鏁版嵁搴撹繛鎺ュけ璐�  璇疯仈绯荤鐞嗗憳锛�");
+            e.printStackTrace();
+        }
+        return druidProperties.dataSource(dataSource);
+    }
+
+
+
+    private DruidDataSource creatSqlServer(String enabled, String ip,String port,String db,String user,String password) throws SQLException {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties properties = new Properties();
+        properties.setProperty("druid.enabled", enabled);
+        properties.setProperty("druid.driverClassName","com.microsoft.sqlserver.jdbc.SQLServerDriver");
+        properties.setProperty("druid.url","jdbc:sqlserver://"+ ip+":"+ port+";DatabaseName="+ db+
+                ";&characterEncoding=utf8");
+        properties.setProperty("druid.username", user);
+        properties.setProperty("druid.password", password);
+        dataSource.restart(properties);
+        return dataSource;
+    }
+
+    private DruidDataSource creatMysql(String enabled, String ip,String port,String db,String user,String password) throws SQLException {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties properties = new Properties();
+        properties.setProperty("druid.enabled",enabled);
+        properties.setProperty("druid.url","jdbc:mysql://"+ip+":"+port+"/"+db+"" +
+                "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8");
+        properties.setProperty("druid.username",user);
+        properties.setProperty("druid.password",password);
+        dataSource.restart(properties);
+        return dataSource;
+    }
+
+    private DruidDataSource creatOracle(String enabled, String ip,String port,String db,String user,String password) throws SQLException {
+        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
+        Properties properties = new Properties();
+        properties.setProperty("druid.enabled",enabled);
+        properties.setProperty("druid.driverClassName","oracle.jdbc.OracleDriver");
+        properties.setProperty("druid.url","jdbc:oracle:thin:@//"+ip+"/"+db);
+        properties.setProperty("druid.username",user);
+        properties.setProperty("druid.password",password);
+        dataSource.restart(properties);
+        return dataSource;
+    }
+
 }
diff --git a/ltkj-hosp/src/main/java/com/ltkj/db/DruidProperties.java b/ltkj-hosp/src/main/java/com/ltkj/db/DruidProperties.java
new file mode 100644
index 0000000..c34c969
--- /dev/null
+++ b/ltkj-hosp/src/main/java/com/ltkj/db/DruidProperties.java
@@ -0,0 +1,61 @@
+package com.ltkj.db;
+
+import com.alibaba.druid.pool.DruidDataSource;
+
+/**
+ * druid 閰嶇疆灞炴��
+ *
+ * @author ruoyi
+ */
+public class DruidProperties {
+
+    private int initialSize=5;
+
+    private int minIdle=10;
+
+    private int maxActive=20;
+
+    private int maxWait=60000;
+
+    private int timeBetweenEvictionRunsMillis=60000;
+
+    private int minEvictableIdleTimeMillis=300000;
+
+    private int maxEvictableIdleTimeMillis=900000;
+
+
+    private boolean testWhileIdle=true;
+
+    private boolean testOnBorrow=false;
+
+    private boolean testOnReturn=false;
+
+    public DruidDataSource dataSource(DruidDataSource datasource) {
+        /** 閰嶇疆鍒濆鍖栧ぇ灏忋�佹渶灏忋�佹渶澶� */
+        datasource.setInitialSize(initialSize);
+        datasource.setMaxActive(maxActive);
+        datasource.setMinIdle(minIdle);
+
+        /** 閰嶇疆鑾峰彇杩炴帴绛夊緟瓒呮椂鐨勬椂闂� */
+        datasource.setMaxWait(maxWait);
+
+        /** 閰嶇疆闂撮殧澶氫箙鎵嶈繘琛屼竴娆℃娴嬶紝妫�娴嬮渶瑕佸叧闂殑绌洪棽杩炴帴锛屽崟浣嶆槸姣 */
+        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
+
+        /** 閰嶇疆涓�涓繛鎺ュ湪姹犱腑鏈�灏忋�佹渶澶х敓瀛樼殑鏃堕棿锛屽崟浣嶆槸姣 */
+        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
+        datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
+
+        /**
+         * 鐢ㄦ潵妫�娴嬭繛鎺ユ槸鍚︽湁鏁堢殑sql锛岃姹傛槸涓�涓煡璇㈣鍙ワ紝甯哥敤select 'x'銆傚鏋渧alidationQuery涓簄ull锛宼estOnBorrow銆乼estOnReturn銆乼estWhileIdle閮戒笉浼氳捣浣滅敤銆�
+         */
+//        datasource.setValidationQuery(validationQuery);
+        /** 寤鸿閰嶇疆涓簍rue锛屼笉褰卞搷鎬ц兘锛屽苟涓斾繚璇佸畨鍏ㄦ�с�傜敵璇疯繛鎺ョ殑鏃跺�欐娴嬶紝濡傛灉绌洪棽鏃堕棿澶т簬timeBetweenEvictionRunsMillis锛屾墽琛寁alidationQuery妫�娴嬭繛鎺ユ槸鍚︽湁鏁堛�� */
+        datasource.setTestWhileIdle(testWhileIdle);
+        /** 鐢宠杩炴帴鏃舵墽琛寁alidationQuery妫�娴嬭繛鎺ユ槸鍚︽湁鏁堬紝鍋氫簡杩欎釜閰嶇疆浼氶檷浣庢�ц兘銆� */
+        datasource.setTestOnBorrow(testOnBorrow);
+        /** 褰掕繕杩炴帴鏃舵墽琛寁alidationQuery妫�娴嬭繛鎺ユ槸鍚︽湁鏁堬紝鍋氫簡杩欎釜閰嶇疆浼氶檷浣庢�ц兘銆� */
+        datasource.setTestOnReturn(testOnReturn);
+        return datasource;
+    }
+}
diff --git a/ltkj-hosp/src/main/java/com/ltkj/db/HospDynamicDataSource.java b/ltkj-hosp/src/main/java/com/ltkj/db/HospDynamicDataSource.java
index 06267f4..f615185 100644
--- a/ltkj-hosp/src/main/java/com/ltkj/db/HospDynamicDataSource.java
+++ b/ltkj-hosp/src/main/java/com/ltkj/db/HospDynamicDataSource.java
@@ -1,24 +1,30 @@
 package com.ltkj.db;
 
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 import javax.sql.DataSource;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
+@Slf4j
 public class HospDynamicDataSource extends AbstractRoutingDataSource {
 
     private final Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(); // 瀛樺偍鎵�鏈夋暟鎹簮
 
     @Override
     protected Object determineCurrentLookupKey() {
-        return DataSourceContextHolder.getDataSourceKey(); // 鏍规嵁涓婁笅鏂囪幏鍙栧綋鍓嶆暟鎹簮鐨勯敭
+        String key = DataSourceContextHolder.getDataSourceKey();
+        log.info("褰撳墠鏁版嵁婧� ->{}",key);
+        return key; // 鏍规嵁涓婁笅鏂囪幏鍙栧綋鍓嶆暟鎹簮鐨勯敭
     }
 
     // 娣诲姞鐩爣鏁版嵁婧�
     public void addTargetDataSource(String key, DataSource dataSource) {
-        targetDataSources.put(key, dataSource);
-        super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 鏇存柊鐩爣鏁版嵁婧�
-        super.afterPropertiesSet(); // 閲嶆柊鍒濆鍖栨暟鎹簮
+        if (dataSource != null) {
+            targetDataSources.put(key, dataSource);
+            super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); // 鏇存柊鐩爣鏁版嵁婧�
+            super.afterPropertiesSet(); // 閲嶆柊鍒濆鍖栨暟鎹簮
+        }
     }
 
     // 鍏佽澶栭儴璁块棶鎵�鏈夌洰鏍囨暟鎹簮
diff --git a/pom.xml b/pom.xml
index 00a7d92..a56b3d9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -126,6 +126,18 @@
                 <groupId>com.alibaba</groupId>
                 <artifactId>druid-spring-boot-starter</artifactId>
                 <version>${druid.version}</version>
+                <exclusions>
+                    <exclusion>
+                        <groupId>com.alibaba</groupId>
+                        <artifactId>druid</artifactId>
+                    </exclusion>
+                </exclusions>
+            </dependency>
+
+            <dependency>
+                <groupId>com.alibaba</groupId>
+                <artifactId>druid</artifactId>
+                <version>${druid.version}</version>
             </dependency>
 
             <!-- 瑙f瀽瀹㈡埛绔搷浣滅郴缁熴�佹祻瑙堝櫒绛� -->

--
Gitblit v1.8.0