2025-08-04 | zhaowenxuan | ![]() |
2025-08-04 | zhaowenxuan | ![]() |
2025-08-04 | zhaowenxuan | ![]() |
2025-08-04 | zhaowenxuan | ![]() |
src/main/java/com/example/config/DruidConfig.java
@@ -30,7 +30,7 @@ * @Date: 2024/7/1 10:27 */ @Slf4j @Configuration //@Configuration public class DruidConfig { @Autowired private ConfigValue configValue; src/main/java/com/example/config/db/DataSourceConfig.java
New file @@ -0,0 +1,141 @@ package com.example.config.db; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.example.config.ConfigValue; import com.example.config.DruidProperties; import com.example.enums.DataSourceType; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; @Slf4j @Configuration public class DataSourceConfig { private static final String DEFAULT_DATA_SOURCE_KEY = "default"; // 主库的标识 private final Map<String, DataSource> dataSourceCache = new HashMap<>(); // 数据源缓存 @Autowired private ConfigValue configValue; private String primaryUrl; private String primaryPort; private String primaryUsername; private String primaryPassword; private String dbUrl; private String dbName; @Autowired private DruidProperties druidProperties; @Bean(name = "hospDynamicDataSources") public DataSource hospDynamicDataSources() { HospDynamicDataSource dynamicDataSource = new HospDynamicDataSource(); Map<String, String> configMap = configValue.getConfigMap(); dbUrl = configMap.get("ip"); dbName = configMap.get("name"); primaryPassword = configMap.get("password"); primaryPort = configMap.get("prot"); primaryUsername = configMap.get("username"); String url = "jdbc:mysql://" + dbUrl + ":" + primaryPort + "/" + dbName; dynamicDataSource.addTargetDataSource(DEFAULT_DATA_SOURCE_KEY, createDataSource(url, primaryUsername, primaryPassword)); DataSource masterDataSource = masterDataSource(druidProperties); dynamicDataSource.addTargetDataSource(DataSourceType.MASTER.name(),masterDataSource); dataSourceCache.put(DataSourceType.MASTER.name(), masterDataSource); dynamicDataSource.setDefaultTargetDataSource(dynamicDataSource.getTargetDataSources().get(DEFAULT_DATA_SOURCE_KEY)); // 设置默认数据源 return dynamicDataSource; } // 动态创建数据源 private DataSource createDataSource(String url, String username, String password) { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } // 根据用户 ID 动态获取数据源 public void addDataSource(String dbName) { Map<String, String> configMap = configValue.getConfigMap(); dbUrl = configMap.get("ip"); primaryPassword = configMap.get("password"); primaryPort = configMap.get("prot"); primaryUsername = configMap.get("username"); // 检查缓存中是否已经存在该数据源 if (!dataSourceCache.containsKey(dbName)) { synchronized (this) { String url = "jdbc:mysql://" + dbUrl + ":" + primaryPort + "/" + dbName; DataSource dataSource = createDataSource(url, primaryUsername, primaryPassword); dataSourceCache.put(dbName, dataSource); HospDynamicDataSource dynamicDataSource = (HospDynamicDataSource) hospDynamicDataSources(); dynamicDataSource.addTargetDataSource(dbName, dataSource); } } } public DataSource masterDataSource(DruidProperties druidProperties){ DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); Map<String, String> configMap = configValue.getConfigMap(); try { // 获取属性值并赋值 Properties properties = new Properties(); // 这里是测试写法,具体的value可以通过请求参数传递过来 properties.setProperty("druid.url","jdbc:mysql://"+configMap.get("ip")+":"+configMap.get("prot")+"/"+configMap.get("name")+"" + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true"); properties.setProperty("druid.username",configMap.get("username")); properties.setProperty("druid.password",configMap.get("password")); dataSource.restart(properties); log.info("数据库连接成功!!!"); } catch (Exception e) { log.error("数据库连接失败 请联系管理员!",e); } 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; } } src/main/java/com/example/config/db/DataSourceContextHolder.java
New file @@ -0,0 +1,17 @@ package com.example.config.db; public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public static void setDataSourceKey(String key) { contextHolder.set(key); } public static String getDataSourceKey() { return contextHolder.get(); } public static void clear() { contextHolder.remove(); } } src/main/java/com/example/config/db/HospDynamicDataSource.java
New file @@ -0,0 +1,36 @@ package com.example.config.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(); } public void addTargetDataSource(String key, DataSource dataSource) { if (dataSource != null) { targetDataSources.put(key, dataSource); super.setTargetDataSources(new ConcurrentHashMap<>(targetDataSources)); super.afterPropertiesSet(); } } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { super.setTargetDataSources(targetDataSources); } public Map<Object, Object> getTargetDataSources() { return targetDataSources; } } src/main/java/com/example/domain/DictHosp.java
@@ -177,134 +177,10 @@ */ private byte[] imgbase64; private Integer isAutoAsyncJg; private Integer isTbHisProject; @TableField(exist = false) private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } DictHosp other = (DictHosp) that; return (this.getHospAreaId() == null ? other.getHospAreaId() == null : this.getHospAreaId().equals(other.getHospAreaId())) && (this.getHospAreaName() == null ? other.getHospAreaName() == null : this.getHospAreaName().equals(other.getHospAreaName())) && (this.getHospid() == null ? other.getHospid() == null : this.getHospid().equals(other.getHospid())) && (this.getHospName() == null ? other.getHospName() == null : this.getHospName().equals(other.getHospName())) && (this.getCode() == null ? other.getCode() == null : this.getCode().equals(other.getCode())) && (this.getWbm() == null ? other.getWbm() == null : this.getWbm().equals(other.getWbm())) && (this.getSpell() == null ? other.getSpell() == null : this.getSpell().equals(other.getSpell())) && (this.getAreaid() == null ? other.getAreaid() == null : this.getAreaid().equals(other.getAreaid())) && (this.getAreaName() == null ? other.getAreaName() == null : this.getAreaName().equals(other.getAreaName())) && (this.getMainHospArea() == null ? other.getMainHospArea() == null : this.getMainHospArea().equals(other.getMainHospArea())) && (this.getPrincipal() == null ? other.getPrincipal() == null : this.getPrincipal().equals(other.getPrincipal())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getPlaitBed() == null ? other.getPlaitBed() == null : this.getPlaitBed().equals(other.getPlaitBed())) && (this.getOpenBed() == null ? other.getOpenBed() == null : this.getOpenBed().equals(other.getOpenBed())) && (this.getBuildDate() == null ? other.getBuildDate() == null : this.getBuildDate().equals(other.getBuildDate())) && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())) && (this.getCreateBy() == null ? other.getCreateBy() == null : this.getCreateBy().equals(other.getCreateBy())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (this.getUpdateBy() == null ? other.getUpdateBy() == null : this.getUpdateBy().equals(other.getUpdateBy())) && (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime())) && (this.getOrderNum() == null ? other.getOrderNum() == null : this.getOrderNum().equals(other.getOrderNum())) && (this.getEffective() == null ? other.getEffective() == null : this.getEffective().equals(other.getEffective())) && (this.getCreateByName() == null ? other.getCreateByName() == null : this.getCreateByName().equals(other.getCreateByName())) && (this.getUpdateByName() == null ? other.getUpdateByName() == null : this.getUpdateByName().equals(other.getUpdateByName())) && (this.getDeleted() == null ? other.getDeleted() == null : this.getDeleted().equals(other.getDeleted())) && (this.getCreateId() == null ? other.getCreateId() == null : this.getCreateId().equals(other.getCreateId())) && (this.getUpdateId() == null ? other.getUpdateId() == null : this.getUpdateId().equals(other.getUpdateId())) && (this.getSecretKey() == null ? other.getSecretKey() == null : this.getSecretKey().equals(other.getSecretKey())) && (this.getExpirationTime() == null ? other.getExpirationTime() == null : this.getExpirationTime().equals(other.getExpirationTime())) && (this.getDbname() == null ? other.getDbname() == null : this.getDbname().equals(other.getDbname())) && (this.getBeanName() == null ? other.getBeanName() == null : this.getBeanName().equals(other.getBeanName())) && (Arrays.equals(this.getImgbase64(), other.getImgbase64())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getHospAreaId() == null) ? 0 : getHospAreaId().hashCode()); result = prime * result + ((getHospAreaName() == null) ? 0 : getHospAreaName().hashCode()); result = prime * result + ((getHospid() == null) ? 0 : getHospid().hashCode()); result = prime * result + ((getHospName() == null) ? 0 : getHospName().hashCode()); result = prime * result + ((getCode() == null) ? 0 : getCode().hashCode()); result = prime * result + ((getWbm() == null) ? 0 : getWbm().hashCode()); result = prime * result + ((getSpell() == null) ? 0 : getSpell().hashCode()); result = prime * result + ((getAreaid() == null) ? 0 : getAreaid().hashCode()); result = prime * result + ((getAreaName() == null) ? 0 : getAreaName().hashCode()); result = prime * result + ((getMainHospArea() == null) ? 0 : getMainHospArea().hashCode()); result = prime * result + ((getPrincipal() == null) ? 0 : getPrincipal().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getPlaitBed() == null) ? 0 : getPlaitBed().hashCode()); result = prime * result + ((getOpenBed() == null) ? 0 : getOpenBed().hashCode()); result = prime * result + ((getBuildDate() == null) ? 0 : getBuildDate().hashCode()); result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); result = prime * result + ((getCreateBy() == null) ? 0 : getCreateBy().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + ((getUpdateBy() == null) ? 0 : getUpdateBy().hashCode()); result = prime * result + ((getUpdateTime() == null) ? 0 : getUpdateTime().hashCode()); result = prime * result + ((getOrderNum() == null) ? 0 : getOrderNum().hashCode()); result = prime * result + ((getEffective() == null) ? 0 : getEffective().hashCode()); result = prime * result + ((getCreateByName() == null) ? 0 : getCreateByName().hashCode()); result = prime * result + ((getUpdateByName() == null) ? 0 : getUpdateByName().hashCode()); result = prime * result + ((getDeleted() == null) ? 0 : getDeleted().hashCode()); result = prime * result + ((getCreateId() == null) ? 0 : getCreateId().hashCode()); result = prime * result + ((getUpdateId() == null) ? 0 : getUpdateId().hashCode()); result = prime * result + ((getSecretKey() == null) ? 0 : getSecretKey().hashCode()); result = prime * result + ((getExpirationTime() == null) ? 0 : getExpirationTime().hashCode()); result = prime * result + ((getDbname() == null) ? 0 : getDbname().hashCode()); result = prime * result + ((getBeanName() == null) ? 0 : getBeanName().hashCode()); result = prime * result + (Arrays.hashCode(getImgbase64())); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", hospAreaId=").append(hospAreaId); sb.append(", hospAreaName=").append(hospAreaName); sb.append(", hospid=").append(hospid); sb.append(", hospName=").append(hospName); sb.append(", code=").append(code); sb.append(", wbm=").append(wbm); sb.append(", spell=").append(spell); sb.append(", areaid=").append(areaid); sb.append(", areaName=").append(areaName); sb.append(", mainHospArea=").append(mainHospArea); sb.append(", principal=").append(principal); sb.append(", phone=").append(phone); sb.append(", plaitBed=").append(plaitBed); sb.append(", openBed=").append(openBed); sb.append(", buildDate=").append(buildDate); sb.append(", remark=").append(remark); sb.append(", createBy=").append(createBy); sb.append(", createTime=").append(createTime); sb.append(", updateBy=").append(updateBy); sb.append(", updateTime=").append(updateTime); sb.append(", orderNum=").append(orderNum); sb.append(", effective=").append(effective); sb.append(", createByName=").append(createByName); sb.append(", updateByName=").append(updateByName); sb.append(", deleted=").append(deleted); sb.append(", createId=").append(createId); sb.append(", updateId=").append(updateId); sb.append(", secretKey=").append(secretKey); sb.append(", expirationTime=").append(expirationTime); sb.append(", dbname=").append(dbname); sb.append(", beanName=").append(beanName); sb.append(", imgbase64=").append(imgbase64); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } } } src/main/java/com/example/factory/ServiceFactory.java
@@ -61,6 +61,8 @@ return "ShanXiQinBaoJiSsyjyy"; case "shanxiqinxatlgcyy": return "ShanXiQinXiAnXatlgcyy"; case "shanxiqinwhyy": return "ShanXiQinWeiNanWhyy"; default: throw new RuntimeException("找不到对应的医院服务配置:" + hospName); } src/main/java/com/example/mapper/SqlMapper.java
New file @@ -0,0 +1,14 @@ package com.example.mapper; import org.apache.ibatis.annotations.Select; /** * @Company: 西安路泰科技有限公司 * @Author: zhaowenxuan * @Date: 2025/7/30 10:10 */ public interface SqlMapper { @Select("call pro_tb_his_project()") void pro_tb_his_project(); } src/main/java/com/example/scheudleds/DictSyncCommon.java
@@ -1,8 +1,11 @@ package com.example.scheudleds; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.example.config.db.DataSourceConfig; import com.example.config.db.DataSourceContextHolder; import com.example.domain.DictHosp; import com.example.factory.ServiceFactory; import com.example.mapper.SqlMapper; import com.example.service.DictHospService; import com.example.service.HisService; import lombok.extern.slf4j.Slf4j; @@ -31,23 +34,40 @@ @Autowired private DictHospService dictHospService; @Autowired private SqlMapper sqlMapper; @Autowired private DataSourceConfig dataSourceConfig; @Scheduled(cron = "0 0 22 * * ?") public void executeTasks() { // List<String> list = Arrays.asList("shanxiqinxamjyy","shanxiqinpbkwyy","shanxiqinjdczgzyy","shanxiqinsqyy"); List<String> list = dictHospService.list(new LambdaQueryWrapper<DictHosp>().isNotNull(DictHosp::getBeanName)) .stream().map(DictHosp::getBeanName).collect(Collectors.toList()); // List<String> list = dictHospService.list(new LambdaQueryWrapper<DictHosp>().isNotNull(DictHosp::getBeanName)) // .stream().map(DictHosp::getBeanName).collect(Collectors.toList()); List<DictHosp> list = dictHospService.list(new LambdaQueryWrapper<DictHosp>().isNotNull(DictHosp::getBeanName)); log.info("开始执行定时任务:{}", System.currentTimeMillis()); try { for (String hosp : list) { for (DictHosp hosp : list) { executorService.submit(() -> { try { log.info("开始同步医院数据:{}", hosp); HisService hisService = serviceFactory.getService(hosp); hisService.syncDict(hosp); log.info("完成同步医院数据:{}", hosp); String beanName = hosp.getBeanName(); log.info("开始同步医院数据:{}", beanName); HisService hisService = serviceFactory.getService(beanName); hisService.syncDict(beanName); log.info("完成同步医院数据:{}", beanName); } catch (Exception e) { log.error("同步医院数据失败,医院:{},异常:{}", hosp, e.getMessage()); log.error("同步医院数据失败,医院:{}", hosp.getBeanName(), e); } if (hosp.getIsTbHisProject() != null && hosp.getIsTbHisProject() == 1) { try { dataSourceConfig.addDataSource(hosp.getDbname()); DataSourceContextHolder.setDataSourceKey(hosp.getDbname()); sqlMapper.pro_tb_his_project(); } catch (Exception e) { log.error("调用同步存储过程失败,医院:{}", hosp.getBeanName(), e); }finally { DataSourceContextHolder.clear(); } } }); } src/main/java/com/example/service/shanjianyi/shanxiqin/weinan/whyy/DictionaryUtilShanXiWeiNanWhyy.java
New file @@ -0,0 +1,467 @@ package com.example.service.shanjianyi.shanxiqin.weinan.whyy; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.example.domain.DictCommonHisConfig; import com.example.domain.HisSyncDict; import com.example.mapper.HisSyncDictMapper; import com.example.service.DictCommonHisConfigService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.sql.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * @Company: 西安路泰科技有限公司 * @Author: zhaowenxuan * @Date: 2025/3/18 11:19 */ @Slf4j @Component public class DictionaryUtilShanXiWeiNanWhyy { @Autowired private HisSyncDictMapper hisSyncDictMapper; @Autowired private DictCommonHisConfigService dictCommonHisConfigService; private static final int SIZE = 100; // 分页每次1000条 static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (Exception e) { System.out.println("静态代码块异常 ->"+e.getMessage()); } } /** * 进行同步 */ public void exec(List<HisSyncDict> hisSyncDicts, String token){ DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital("whyy"); log.info("开始执行同步"); Connection connection = getConnection(config); if (connection == null) return; for (HisSyncDict hisSyncDict : hisSyncDicts) { boolean isFormatJson = false; if (hisSyncDict.getDictName().equals("getKeShizd") || hisSyncDict.getDictName().equals("getKeShiByConditionszd") || hisSyncDict.getDictName().equals("getShouFeiXmzd") || hisSyncDict.getDictName().equals("getListYiShengZd") ) isFormatJson = true; hisSyncDict.setDictName(hisSyncDict.getHospId()+"_"+hisSyncDict.getDictName()); extracted(config.getDbName(), connection, hisSyncDict,token,isFormatJson,config); } try { connection.close(); } catch (SQLException ignored) { } hisSyncDictMapper.proSyncCommonDict(); log.info("执行同步完毕"); } private void extracted(String name, Connection connection, HisSyncDict hisSyncDict,String token,Boolean isFormatJson,DictCommonHisConfig config) { String method = hisSyncDict.getDictName(); log.info("开始请求代码 ->{}", method); String tabName = "ltkj_" + method.toLowerCase(); boolean isLimit = false; int page = 1; int maxPage = 1; String params = hisSyncDict.getParams(); params = params.replace("${pageIndex}",String.valueOf(page)); params = params.replace("${pageSize}",String.valueOf(SIZE)); JSONObject object = JSONUtil.parseObj(params); if (hisSyncDict.getIsLimit() == 1) { isLimit = true; } log.info("请求接口 ->{}, 请求参数 ->{}", config.getHisUrl()+hisSyncDict.getUrl(), object); JSONObject entries = execRequest(config,object.toString(),hisSyncDict,token); log.info("请求返回 ->{}", entries.toString()); if (isFormatJson){ if ("1".equals(entries.getStr("returnCode"))) { JSONObject response = entries.getJSONObject("returnData"); try { dropTable(tabName, connection); } catch (SQLException e) { log.error("删除表异常 ->{}", e.getMessage()); } if (isLimit) { maxPage = LimitInsertData(connection, tabName, response, name, page); log.info("计算页码为 ->{}", maxPage); if (maxPage > 1) { for (page = 2; page <= maxPage; page++) { params = hisSyncDict.getParams(); params = params.replace("${pageIndex}",String.valueOf(page)); params = params.replace("${pageSize}",String.valueOf(SIZE)); object = JSONUtil.parseObj(params); log.info("请求接口 ->{}, 请求参数 ->{}", config.getHisUrl()+hisSyncDict.getUrl(), object.toString()); entries = execRequest(config,object.toString(),hisSyncDict,token); log.info("请求返回 ->{}", entries.toString()); response = entries.getJSONObject("returnData"); if ("1".equals(entries.getStr("returnCode"))) { LimitInsertData(connection, tabName, response, name, page); } else { log.error("{} 请求失败:{}", method, object.toString()); } } } } else { JSONArray resultData = response.getJSONArray("list"); List<JSONObject> list = JSONUtil.toList(resultData, JSONObject.class); for (JSONObject jsonObject : list) { editDataBase(connection, tabName, jsonObject, name); } } } }else { if ("1".equals(entries.getStr("returnCode"))) { Object returnData = entries.get("returnData"); if (returnData instanceof JSONObject){ JSONObject response = entries.getJSONObject("returnData"); try { dropTable(tabName, connection); } catch (SQLException e) { log.error("删除表异常 ->{}", e.getMessage()); } editDataBase(connection, tabName, response, name); }else { JSONArray response = entries.getJSONArray("returnData"); try { dropTable(tabName, connection); List<JSONObject> list = JSONUtil.toList(response, JSONObject.class); for (JSONObject jsonObject : list) { editDataBase(connection, tabName, jsonObject, name); } } catch (SQLException e) { log.error("删除表异常 ->{}", e.getMessage()); } } if (isLimit) { JSONArray response = entries.getJSONArray("returnData"); if (tabName.contains("_getjianchaxmzd")) maxPage = 10000; log.info("计算页码为 ->{}", maxPage); if (maxPage > 1) { for (page = 2; page <= maxPage; page++) { params = hisSyncDict.getParams(); params = params.replace("${pageIndex}",String.valueOf(page)); params = params.replace("${pageSize}",String.valueOf(SIZE)); object = JSONUtil.parseObj(params); log.info("请求接口 ->{}, 请求参数 ->{}", config.getHisUrl()+hisSyncDict.getUrl(), object.toString()); entries = execRequest(config,object.toString(),hisSyncDict,token); log.info("请求返回 ->{}", entries.toString()); response = entries.getJSONArray("returnData"); if (response.isEmpty()) break; List<JSONObject> list = JSONUtil.toList(response, JSONObject.class); for (JSONObject jsonObject : list) { editDataBase(connection, tabName, jsonObject, name); } } } } else { JSONArray response = entries.getJSONArray("returnData"); List<JSONObject> list = JSONUtil.toList(response, JSONObject.class); for (JSONObject jsonObject : list) { editDataBase(connection, tabName, jsonObject, name); } } } } } /** * 针对于分页接口 创建表、插入数据 * * @param connection * @param tabName * @param response * @return */ private int LimitInsertData(Connection connection, String tabName, JSONObject response,String name,Integer page) { JSONArray jsonArray = response.getJSONArray("list"); JSONObject entries = (JSONObject) jsonArray.get(0); int maxPage; // 行数 数据返回的第几行 Integer rowNumber = response.getInt("RowNumber"); // 总条数 Integer totalCount = response.getInt("totalRows"); Integer pageCount = response.getInt("pageCount"); maxPage = (totalCount + 100 - 1) / 100; log.info("请求返回总条数 ->{},当前页 ->{},总页数 ->{}",totalCount,page,maxPage); jsonArray.forEach(obj -> { editDataBase(connection, tabName, (JSONObject) obj,name); }); return pageCount; } /** * 操作数据库 * * @param connection * @param tabName * @param obj */ private void editDataBase(Connection connection, String tabName, JSONObject obj,String name) { try { if (!tabIsExists(connection, tabName,name)) { // 创建表 creatTable(obj, tabName, connection); } } catch (SQLException throwables) { log.error("创建表异常"); log.error(throwables.getSQLState()); log.error(throwables.getMessage()); } // 对比字段 并插入数据 try { operationTable(obj, tabName, connection); } catch (SQLException e) { log.error("对比字段插入数据异常"); log.error(e.getSQLState()); log.error(e.getMessage()); e.printStackTrace(); } } /** * 执行post请求 * * @param params 请求参数 例如: param1=val1¶m2=val2 * @return 请求返回的json转换后的JSONObject对象 */ private JSONObject execRequest(DictCommonHisConfig config,String params,HisSyncDict hisSyncDict,String token) { URL url = null; HttpURLConnection connection = null; OutputStreamWriter writer = null; BufferedReader reader = null; StringBuilder response = new StringBuilder(); try { url = new URL(config.getHisUrl()+hisSyncDict.getUrl()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Authorization", token); log.info("请求接口 ->{}", hisSyncDict.getUrl()); if (hisSyncDict.getUrl().equals("/zhuShuJu/getListYiShengZd") || hisSyncDict.getUrl().equals("/zhuShuJu/getZhiGongPage") || hisSyncDict.getUrl().equals("/zhuShuJu/getJianChaXm")){ connection.setRequestProperty("dangQianYhId","DBA"); if (hisSyncDict.getUrl().equals("/zhuShuJu/getJianChaXm")) connection.setRequestProperty("yuanQuId","1"); } connection.setDoOutput(true); StringBuilder postData = new StringBuilder(); JSONObject jsonObject = JSONUtil.parseObj(params); for (String key : jsonObject.keySet()) { if (postData.length() > 0) { postData.append("&"); } String encode = URLEncoder.encode(key, "UTF-8"); String encode1 = URLEncoder.encode(String.valueOf(jsonObject.get(key)), "UTF-8"); postData.append(encode).append("=").append(encode1); } writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData.toString()); writer.flush(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } return JSONUtil.parseObj(response); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } public Connection getConnection(DictCommonHisConfig config) { // public void setConfigPath(String configPath) { // CONFIG_PATH = configPath; // NAME = configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.name"); // URL = "jdbc:mysql://" + configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.ip") // + ":" + configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.prot") + "/" + NAME + // "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8"; // USER = configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.username"); // PASSWORD = configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.password"); // String apiUrl = configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.his_api_url"); // String apiPort = configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.his_api_port"); // BASE_API_URL = apiUrl+":"+apiPort+configValue.getConfigValue("ShanXi_Qin_BaoJi_Bjxjyy.hisapiappend"); // } try { String url = "jdbc:mysql://" + config.getDbIp() + ":" + config.getDbPort() + "/" + config.getDbName() + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8"; log.info("数据库信息 ->{},{},{}",config.getDbUser(),config.getDbPassword(),url); return DriverManager.getConnection(url,config.getDbUser(),config.getDbPassword()); } catch (Exception throwables) { log.error("获取sql连接失败"); throwables.printStackTrace(); } return null; } /** * 表是否存在 * * @param connection * @param tableName * @return * @throws SQLException */ private Boolean tabIsExists(Connection connection, String tableName,String name) throws SQLException { String tabSql = "SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_name = ?"; PreparedStatement statement = connection.prepareStatement(tabSql); statement.setString(1, name); statement.setString(2, tableName); // log.info("判断表是否存在 sql-> {}", statement.toString()); ResultSet resultSet = statement.executeQuery(); boolean next = resultSet.next(); statement.close(); return next; } /** * 操作表 * * @param tabName * @param connection * @throws SQLException */ private void operationTable(JSONObject jsonObject, String tabName, Connection connection) throws SQLException { List<String> columns = getColumns(tabName, connection); // log.info("当前表字段为 ->{}", columns); ArrayList<String> responseColums = new ArrayList<>(); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { String key = entry.getKey().trim().toLowerCase(); responseColums.add(key); } // log.info("请求返回的字段为 ->{}", responseColums); responseColums.removeAll(columns); // log.info("需要增加的字段 ->{}",responseColums); if (!responseColums.isEmpty()) { // 需要增加字段 并插入数据 for (String colum : responseColums) { String sql = "alter table " + tabName + " add column " + colum + " VARCHAR(200) null"; // log.info("修改字段 ->{}",sql.toString()); Statement statement = connection.createStatement(); statement.executeUpdate(sql); statement.close(); } insertData(tabName, connection, jsonObject); } else { insertData(tabName, connection, jsonObject); } } /** * 插入数据 * * @param tabName * @param connection * @param jsonObject * @throws SQLException */ private void insertData(String tabName, Connection connection, JSONObject jsonObject) throws SQLException { // 插入数据前 先查询数据是否存在 StringBuilder insertSqlBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); insertSqlBuilder.append("insert into ").append(tabName).append(" ("); for (Map.Entry<String, Object> entry : jsonObject.entrySet()) { String defaultVal = entry.getValue().toString(); String key = entry.getKey().trim().toLowerCase(); if (StrUtil.isBlank(defaultVal) || defaultVal.equals("null")) continue; String val = defaultVal.trim().replaceAll("\\s+", "").replace("\\",""); insertSqlBuilder.append(key).append(", "); valueBuilder.append("'").append(val.replaceAll("'","‘")).append("', "); } insertSqlBuilder.append("insert_time, "); String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); valueBuilder.append("'").append(time).append("'").append(", "); insertSqlBuilder.delete(insertSqlBuilder.length() - 2, insertSqlBuilder.length()); valueBuilder.delete(valueBuilder.length() - 2, valueBuilder.length()); insertSqlBuilder.append(") values (").append(valueBuilder).append(")"); // 插入数据 Statement statement = connection.createStatement(); log.info("插入数据 sql-> {}", insertSqlBuilder.toString()); statement.execute(insertSqlBuilder.toString()); statement.close(); } /** * 获取表的列 * * @param tabName * @param connection * @return * @throws SQLException */ private List<String> getColumns(String tabName, Connection connection) throws SQLException { DatabaseMetaData metaData = connection.getMetaData(); ResultSet columns = metaData.getColumns(null, null, tabName, null); ArrayList<String> tabColumns = new ArrayList<>(); while (columns.next()) { String columnName = columns.getString("column_name"); tabColumns.add(columnName); } return tabColumns; } /** * 创建表 * * @param resultDataIndex1 返回数据中的第一个参数 * @param tabName * @param connection * @throws SQLException */ private void creatTable(JSONObject resultDataIndex1, String tabName, Connection connection) throws SQLException { StringBuilder sql = new StringBuilder("CREATE TABLE " + tabName + " ("); for (Map.Entry<String, Object> entry : resultDataIndex1.entrySet()) { String key = entry.getKey().trim().toLowerCase(); sql.append(key).append(" VARCHAR(200) null,"); } sql.append("insert_time").append(" VARCHAR(100) null,"); sql = new StringBuilder(sql.substring(0, sql.length() - 1)); sql.append(");"); log.info("创建表格 -> {}",sql.toString()); Statement statement = connection.createStatement(); statement.execute(sql.toString()); } /** * 删除表 * @param tabName * @param connection * @throws SQLException */ private void dropTable(String tabName,Connection connection) throws SQLException { String sql = "DROP TABLE IF EXISTS " + tabName; Statement statement = connection.createStatement(); statement.executeUpdate(sql); statement.close(); } } src/main/java/com/example/service/shanjianyi/shanxiqin/weinan/whyy/WhyyHisService.java
New file @@ -0,0 +1,614 @@ package com.example.service.shanjianyi.shanxiqin.weinan.whyy; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSON; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.example.config.ConfigValue; import com.example.constant.ApiParamsConstants; import com.example.domain.DictCommonHisConfig; import com.example.domain.HisSyncDict; import com.example.domain.TjFlowingWaterHis; import com.example.service.DictCommonHisConfigService; import com.example.service.HisService; import com.example.utils.AjaxResult; import com.example.utils.FieldNameConverter; import com.example.utils.HttpClientUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.*; import java.util.concurrent.TimeUnit; /** * @Company: 西安路泰科技有限公司 * @Author: zhaowenxuan * @Date: 2025/3/18 10:17 */ @Slf4j @Service("ShanXiQinWeiNanWhyy") public class WhyyHisService implements HisService { @Autowired private DictionaryUtilShanXiWeiNanWhyy syncZd; @Autowired private ConfigValue configValue; // http://oapi.xamjyy.com/OAPI/oauth/token // grant_type:client_credentials // client_id:XFZZQEfXTZ7exhhi // client_secret:05a192176c21edfcc9cf5fa26fc5a9e0c5b131ad // http://oapi.xamjyy.com/OAPI @Autowired private RedisTemplate<Object ,Object> redisTemplate; @Autowired private DictCommonHisConfigService dictCommonHisConfigService; private static final String HOSP_ID = "whyy"; private static final String TJ_HOSP_ID = "shanxiqinwhyy"; //获取token private JSONObject getToken () { String GRANT_TYPE = "client_credentials"; String CLIENT_ID = "XFZZQEfXTZ7exhhi"; String CLIENT_SECRET = "05a192176c21edfcc9cf5fa26fc5a9e0c5b131ad"; Map<String, Object> map = new HashMap<>(); map.put("grant_type", GRANT_TYPE); map.put("client_id", CLIENT_ID); map.put("client_secret", CLIENT_SECRET); // map.put("scope",SCOP); // String post = sendPostTokenFormUrlencoded (HIS_URL+"/oauth/token", map); String his_url = dictCommonHisConfigService.getConfigValByHospitalAndKey(HOSP_ID, "HIS_URL"); String post = HttpClientUtils.sendPostTokenFormUrlencoded(his_url + "/oauth/token", map, null); if (StrUtil.isBlank(post)) return null; return JSONUtil.parseObj(post); } @Override public String jianDang(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("jiuZhenKh", params.get(ApiParamsConstants.CARD_ID)); map.put ("kaiLeiXing","4"); map.put ("xingMing", params.get(ApiParamsConstants.CUS_NAME)); long cusSex = Long.parseLong(params.get(ApiParamsConstants.CUS_SEX).toString()); if(cusSex==0L){ map.put ("xingBie","男"); }else if(cusSex==1L){ map.put ("xingBie","女"); }else { map.put ("xingBie","未知"); } map.put ("shenFenZh", params.get(ApiParamsConstants.CUS_ID_CARD)); map.put ("danWeiBh",params.get(ApiParamsConstants.COMP_ID)); map.put ("chuShengRq", params.get(ApiParamsConstants.CUS_BRITHDAY)); map.put ("lianXiDz", params.get(ApiParamsConstants.CUS_ADDR)); map.put ("lianXiDh", params.get(ApiParamsConstants.CUS_PHONE)); map.put ("feiYongLb",""); map.put ("feiYongXz",""); map.put ("jiLuLy","3"); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); map.put ("caoZuoYuan",config.getCzyId()); map.put ("chongZhiJe",""); map.put ("yiBaoKh",""); map.put ("geRenBh",""); map.put ("yiBaoBrXx",""); map.put ("gongZuoDw",params.get(ApiParamsConstants.COMP_NAME)); map.put ("canBaoXzMc",""); map.put ("muLuBlLb",""); map.put ("kunNanJzDj",""); map.put ("yiLiaoLb",""); map.put ("minZuDm",""); map.put ("minZuMc",""); // 职业编码 String post = sendPost(config.getHisUrl() + "/menZhenJz/jianDang", map); JSONObject jsonObject = JSONUtil.parseObj(post); if (jsonObject.getStr("returnCode").equals("1")) { JSONObject obj = JSONUtil.createObj(); obj.putOpt("code","200"); obj.putOpt("data",jsonObject.getJSONObject("returnData")); return JSONUtil.toJsonStr(obj); }else { JSONObject obj = JSONUtil.createObj(); obj.putOpt("code","500"); return JSONUtil.toJsonStr(obj); } } @Override public String getBingRenXxByShengFenZheng(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); map.put ("caoZuoYuan",config.getCzyId()); map.put ("shenFenZh", params.get(ApiParamsConstants.CUS_ID_CARD)); map.put ("danWeiBh",params.get(ApiParamsConstants.COMP_ID)); //职业编码 String string = sendPostTokenFormUrlencoded(config.getHisUrl() + "/menZhenJz/getBingRenXxByShengFenZheng", map); JSONObject object = JSONUtil.createObj(); if (StrUtil.isBlank(string)){ object.putOpt("code",500); return JSONUtil.toJsonStr(object); } JSONObject entries = JSONUtil.parseObj(string); log.info("获取病人信息返回数据 ->{}", entries); Object returnData = entries.get("returnData"); if (null != returnData && !returnData.toString().equals("null")) { HashMap<String, String> hashMap = new HashMap<>(); JSONArray returnData1 = entries.getJSONArray("returnData"); JSONObject jsonObject = (JSONObject) returnData1.get(0); hashMap.put(ApiParamsConstants.CARD_ID,jsonObject.getStr("jiuZhenKh")); hashMap.put(ApiParamsConstants.PATIONID,jsonObject.getStr("bingRenId")); object.putOpt("code",200); object.putOpt("data",hashMap); return JSONUtil.toJsonStr(object); }else { object.putOpt("code",404); } return JSONUtil.toJsonStr(object); } @Override public String saveBingRenXx(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("bingRenId", params.get(ApiParamsConstants.PATIONID)); map.put ("kaiLeiXing","4"); map.put("jiuZhenKh",params.get(ApiParamsConstants.CARD_ID)); map.put ("xingMing", params.get(ApiParamsConstants.CUS_NAME)); Long cusSex = Long.parseLong(params.get(ApiParamsConstants.CUS_SEX).toString()); if (cusSex == 0L) { map.put("xingBie", "男"); } else if (cusSex == 1L) { map.put("xingBie", "女"); } else { map.put("xingBie", "未知"); } map.put ("shenFenZh", params.get(ApiParamsConstants.CUS_ID_CARD)); map.put ("danWeiBh",""); map.put ("chuShengRq", params.get(ApiParamsConstants.CUS_BRITHDAY)); map.put ("lianXiDz", params.get(ApiParamsConstants.CUS_ADDR)); map.put ("lianXiDh", params.get(ApiParamsConstants.CUS_PHONE)); map.put ("feiYongLb",""); map.put ("feiYongXz",""); map.put ("jiLuLy","3"); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); map.put ("caoZuoYuan",config.getCzyId()); //职业编码 String post = sendPost(config.getHisUrl() + "/menZhenJz/saveBingRenXx", map); JSONObject jsonObject = JSONUtil.parseObj(post); if (jsonObject.getStr("returnCode").equals("1")) { JSONObject obj = JSONUtil.createObj(); obj.putOpt("code","200"); obj.putOpt("data",jsonObject.getJSONObject("returnData")); return JSONUtil.toJsonStr(obj); }else { JSONObject obj = JSONUtil.createObj(); obj.putOpt("code","500"); return JSONUtil.toJsonStr(obj); } } @Override public String getListDaiShouFei(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("bingRenId",params.get(ApiParamsConstants.PATIONID)); map.put ("jiuZhenKh",params.get(ApiParamsConstants.CARD_ID)); map.put ("yuanQuId","1"); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); String post = sendPost(config.getHisUrl() + "/shouFei/getListDaiShouFei", map); JSONObject jsonObject = JSONUtil.parseObj(post); if (jsonObject.getStr("returnCode").equals("1")) { JSONObject data = jsonObject.getJSONObject("returnData"); JSONArray list = data.getJSONArray("dtoMzFeiyong1List"); JSONArray list1 = data.getJSONArray("dtoMzFeiYong2List"); JSONObject result = JSONUtil.createObj(); result.putOpt("list1",list); result.putOpt("list2",list1); return AjaxResult.success(result); }else { return AjaxResult.error(post); } } @Override public String createMenZhenFy(Map<String, Object> params) { DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); Map<String, Object> map = new HashMap<> (); map.put ("bingRenId",params.get(ApiParamsConstants.PATIONID)); map.put ("jiuZhenKh",params.get(ApiParamsConstants.CARD_ID)); map.put ("caoZuoYuan",config.getCzyId()); map.put ("yuanQuId","1"); map.put ("yingYongId","870101"); map.put ("kaiDanKs",config.getKdks()); map.put ("dengJiLsh",params.get(ApiParamsConstants.Tj_NUM)); map.put ("shouTuiBz",params.get(ApiParamsConstants.SHOU_TUI_STATUS)); map.put ("feiYongMxList",params.get(ApiParamsConstants.FEI_YONG_INFO_LIST)); //职业编码 String post = sendPost(config.getHisUrl() + "/shouFei/createMenZhenFy", map); JSONObject jsonObject = JSONUtil.parseObj(post); if (jsonObject.getInt("returnCode") != 1) return AjaxResult.error(post); JSONObject data = jsonObject.getJSONObject("returnData"); JSONObject result = JSONUtil.createObj(); result.putOpt(ApiParamsConstants.PATIONID,data.getStr(ApiParamsConstants.PATIONID)); result.putOpt(ApiParamsConstants.FEI_YONG_ID,data.getStr(ApiParamsConstants.FEI_YONG_ID)); JSONArray feiYongMxList = data.getJSONArray("feiYongMxList"); ArrayList<TjFlowingWaterHis> tjFlowingWaterHis = new ArrayList<>(); for (Object o : feiYongMxList) { JSONObject entries = (JSONObject) o; TjFlowingWaterHis waterHis = new TjFlowingWaterHis(); waterHis.setId(IdUtil.getSnowflakeNextId()); waterHis.setParentId(data.getStr(ApiParamsConstants.FEI_YONG_ID)); waterHis.setCurrentId(entries.getStr("feiYongMxId")); waterHis.setXmId(entries.getStr("xiangMuId")); tjFlowingWaterHis.add(waterHis); } result.putOpt("mxList",tjFlowingWaterHis); return AjaxResult.success(result); } @Override public String cheXiaoMzFy(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("bingRenId",params.get(ApiParamsConstants.PATIONID)); map.put ("jiuZhenKh",params.get(ApiParamsConstants.CARD_ID)); ArrayList<JSONObject> ids = new ArrayList<>(); String string = params.get(ApiParamsConstants.FEI_YONG_ID_LIST).toString(); String[] split = string.split(","); Arrays.stream(split).forEach(i -> { JSONObject object = JSONUtil.createObj(); object.putOpt("feiYongId",i); ids.add(object); }); map.put ("feiYongIdList",ids); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); //职业编码 String post = sendPost(config.getHisUrl() + "/shouFei/cheXiaoMzFy", map); JSONObject entries = JSONUtil.parseObj(post); if (entries.getStr("returnCode").equals("1")) return AjaxResult.success(); else return AjaxResult.error(post); } @Override public String getKeShi(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("yuanQuId","1"); map.put ("keShiMc",params.get(ApiParamsConstants.DEPT_NAME)); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getKeShi", map); } @Override public String getListYiShengZd(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("yuanQuId","1"); map.put ("keShiMc",params.get(ApiParamsConstants.DEPT_NAME)); map.put ("bianGengSj",""); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getListYiShengZd", map); } @Override public String getShouFeiXm(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("queryString",params.get(ApiParamsConstants.COMMON_QUERY_KEY)); map.put ("bianGengSj",""); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getShouFeiXm", map); } @Override public String getKeShiByConditions(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("xingZhiSx",""); map.put ("queryString",params.get(ApiParamsConstants.COMMON_QUERY_KEY)); map.put ("zuoFeiBz",params.get(ApiParamsConstants.DEPT_ZUOFEI_STATUS)); map.put ("yuanQuId","1"); map.put ("keShiIds",params.get(ApiParamsConstants.DEPT_IDS)); map.put ("ifPlus",""); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getKeShiByConditions", map); } @Override public String getYangBen(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("queryString",params.get(ApiParamsConstants.COMMON_QUERY_KEY)); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getYangBen", map); } @Override public String getListBingQuZd(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("yuanQuId",params.get(ApiParamsConstants.YUANQU_ID)); map.put ("keShiId",params.get(ApiParamsConstants.DEPT_ID)); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getListBingQuZd", map); } @Override public String getZhiGongPage(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("bianGengSj",""); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getZhiGongPage", map); } @Override public String getJianChaXm(Map<String, Object> params) { Map<String, Object> map = new HashMap<> (); map.put ("queryString",params.get(ApiParamsConstants.COMMON_QUERY_KEY)); map.put ("bianGengSj",""); map.put ("pageIndex",params.get(ApiParamsConstants.PAGE_INDEX)); map.put ("pageSize",params.get(ApiParamsConstants.PAGE_SIZE)); //职业编码 DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getJianChaXm", map); } @Override public String getJianYanXm(Map<String, Object> map) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("queryCode",map.get(ApiParamsConstants.COMMON_QUERY_KEY)); hashMap.put("page",map.get(ApiParamsConstants.PAGE_INDEX)); hashMap.put("size",map.get(ApiParamsConstants.PAGE_SIZE)); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getJianYanXm", hashMap); } @Override public String getShouFeiXmJg(Map<String, Object> map) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("shouFeiXmId",map.get(ApiParamsConstants.COMMON_QUERY_KEY)); hashMap.put("jiaGeTx",map.get(ApiParamsConstants.COMMON_QUERY_KEY2)); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getShouFeiXmJg", hashMap); } @Override public String getRongQi(Map<String, Object> map) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("queryString",map.get(ApiParamsConstants.COMMON_QUERY_KEY)); hashMap.put("pageIndex",map.get(ApiParamsConstants.PAGE_INDEX)); hashMap.put("pageSize",map.get(ApiParamsConstants.PAGE_SIZE)); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getRongQi", hashMap); } @Override public String getJyYangBen(Map<String, Object> map) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put("queryString",map.get(ApiParamsConstants.COMMON_QUERY_KEY)); hashMap.put("pageIndex",map.get(ApiParamsConstants.PAGE_INDEX)); hashMap.put("pageSize",map.get(ApiParamsConstants.PAGE_SIZE)); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); return sendPost(config.getHisUrl()+"/zhuShuJu/getYangBen", hashMap); } @Override public String pushZhiFuMsg(String hospName,Map<String, Object> params) { log.info("回调触发 ->{}",params); configValue.refresh(); Map<String, Object> map = new HashMap<> (); map.put ("feiYongId",params.get("feiyongid")); String string = params.get("status").toString(); if (!string.equals("1")) string = "2"; map.put ("yeWuLx",string); // 参数类型区分 map.put("type","1"); HashMap<String, Object> headers = new HashMap<>(); headers.put("hospId",HOSP_ID); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); String post = HttpClientUtils.sendPost(config.getTjUrl() + "/callBack/pushZhiFuMsg", map,headers); JSONObject jsonObject = JSONUtil.parseObj(post); JSONObject obj = JSONUtil.createObj(); if (jsonObject.getStr("code").equals("200")) { obj.putOpt("returnCode",1); obj.putOpt("exceptionContent",""); obj.putOpt("returnData",null); }else { obj.putOpt("returnCode",0); obj.putOpt("exceptionContent",jsonObject.getStr("msg")); obj.putOpt("returnData",null); } return JSONUtil.toJsonStr(obj); } private String sendPost(String url, Map<String, Object> hashMap){ Map<Object, Object> entries = redisTemplate.opsForHash().entries("token:his:"+TJ_HOSP_ID); if (entries != null && !entries.isEmpty()) { String timeStr = entries.get("time").toString(); String expiresInStr = entries.get("expires_in").toString(); long time = Long.parseLong(timeStr); long expiresIn = Long.parseLong(expiresInStr); Instant tokenExpirationTime = Instant.ofEpochSecond(time).plusSeconds(expiresIn); Instant now = Instant.now(); if (now.isAfter(tokenExpirationTime)){ return refreshToken(url,hashMap,"json"); }else { String accessToken = entries.get("access_token").toString(); String tokenType = entries.get("token_type").toString(); String string = HttpClientUtils.sendPostToken(url, hashMap, tokenType + " " + accessToken); if(StrUtil.isNotBlank(string)){ JSON json = FieldNameConverter.convertFieldNames(JSONUtil.parse(string)); return JSONUtil.toJsonStr(json); } else return JSONUtil.createObj().toString(); } }else { return refreshToken(url, hashMap,"json"); } } private String sendPostTokenFormUrlencoded(String url, Map<String, Object> hashMap){ Map<Object, Object> entries = redisTemplate.opsForHash().entries("token:his:"+TJ_HOSP_ID); if (!entries.isEmpty()) { String timeStr = entries.get("time").toString(); String expiresInStr = entries.get("expires_in").toString(); long time = Long.parseLong(timeStr); long expiresIn = Long.parseLong(expiresInStr); Instant tokenExpirationTime = Instant.ofEpochSecond(time).plusSeconds(expiresIn); Instant now = Instant.now(); if (now.isAfter(tokenExpirationTime)){ return refreshToken(url,hashMap,"url"); }else { String accessToken = entries.get("access_token").toString(); String tokenType = entries.get("token_type").toString(); String string = HttpClientUtils.sendPostTokenFormUrlencoded(url, hashMap, tokenType + " " + accessToken); return StrUtil.isNotBlank(string) ? string : JSONUtil.createObj().toString(); } }else { return refreshToken(url, hashMap,"url"); } } private String sendPostTokenFormData(String url, Map<String, Object> hashMap){ Map<Object, Object> entries = redisTemplate.opsForHash().entries("token:his:"+TJ_HOSP_ID); if (entries != null && !entries.isEmpty()) { String timeStr = entries.get("time").toString(); String expiresInStr = entries.get("expires_in").toString(); long time = Long.parseLong(timeStr); long expiresIn = Long.parseLong(expiresInStr); Instant tokenExpirationTime = Instant.ofEpochSecond(time).plusSeconds(expiresIn); Instant now = Instant.now(); if (now.isAfter(tokenExpirationTime)){ return refreshToken(url,hashMap,"form"); }else { String accessToken = entries.get("access_token").toString(); String tokenType = entries.get("token_type").toString(); String string = HttpClientUtils.sendPostTokenFormData(url, hashMap, tokenType + " " + accessToken); if(StrUtil.isNotBlank(string)){ JSON json = FieldNameConverter.convertFieldNames(JSONUtil.parse(string)); return JSONUtil.toJsonStr(json); }else return JSONUtil.createObj().toString(); } }else { return refreshToken(url, hashMap,"form"); } } private String refreshToken(String url, Map<String, Object> hashMap,String type) { JSONObject parseObj = getToken(); if (parseObj != null) { Integer expiresIn = parseObj.getInt("expires_in"); if (expiresIn != null) { parseObj.putOpt("time", Instant.now().getEpochSecond()); redisTemplate.opsForHash().putAll("token:his:"+TJ_HOSP_ID, parseObj); redisTemplate.expire("token:his:"+TJ_HOSP_ID, expiresIn - 10, TimeUnit.SECONDS); String accessToken = parseObj.getStr("access_token"); String tokenType = parseObj.getStr("token_type"); switch (type){ case "json": String string = HttpClientUtils.sendPostToken(url, hashMap, tokenType + " " + accessToken); if(StrUtil.isNotBlank(string)){ JSON json = FieldNameConverter.convertFieldNames(JSONUtil.parse(string)); return JSONUtil.toJsonStr(json); } else return JSONUtil.createObj().toString(); case "form": String string1 = HttpClientUtils.sendPostTokenFormData(url, hashMap, tokenType + " " + accessToken); if(StrUtil.isNotBlank(string1)){ JSON json = FieldNameConverter.convertFieldNames(JSONUtil.parse(string1)); return JSONUtil.toJsonStr(json); } else return JSONUtil.createObj().toString(); case "url": String string2 = HttpClientUtils.sendPostTokenFormUrlencoded(url, hashMap, tokenType + " " + accessToken); if(StrUtil.isNotBlank(string2)){ JSON json = FieldNameConverter.convertFieldNames(JSONUtil.parse(string2)); return JSONUtil.toJsonStr(json); } else return JSONUtil.createObj().toString(); } } } return JSONUtil.createObj().toString(); } @Override public void syncDict(String hospName) { HashMap<String, Object> map = new HashMap<>(); map.put("hosp",TJ_HOSP_ID); HashMap<String, Object> headers = new HashMap<>(); headers.put("hospId",HOSP_ID); DictCommonHisConfig config = dictCommonHisConfigService.getConfigByHospital(HOSP_ID); String post = HttpClientUtils.sendPost(config.getTjUrl() + "/callBack/getZdList", map,headers); JSONArray jsonArray = JSONUtil.parseObj(post).getJSONArray("data"); if (jsonArray != null && !jsonArray.isEmpty()) { List<HisSyncDict> list = jsonArray.toList(HisSyncDict.class); String token = ""; Map<Object, Object> entries = redisTemplate.opsForHash().entries("token:his:"+TJ_HOSP_ID); if (!entries.isEmpty()) { String timeStr = entries.get("time").toString(); String expiresInStr = entries.get("expires_in").toString(); long time = Long.parseLong(timeStr); Long expiresIn = Long.parseLong(expiresInStr); Instant tokenExpirationTime = Instant.ofEpochSecond(time).plusSeconds(expiresIn); Instant now = Instant.now(); if (now.isAfter(tokenExpirationTime)){ JSONObject parseObj = getToken(); if (parseObj != null) { expiresIn = parseObj.getLong("expires_in"); if (expiresIn != null) { parseObj.putOpt("time", Instant.now().getEpochSecond()); redisTemplate.opsForHash().putAll("token:his:"+TJ_HOSP_ID, parseObj); redisTemplate.expire("token:his:"+TJ_HOSP_ID, expiresIn - 10, TimeUnit.SECONDS); String accessToken = parseObj.getStr("access_token"); String tokenType = parseObj.getStr("token_type"); token = tokenType + " " + accessToken; } } }else { String accessToken = entries.get("access_token").toString(); String tokenType = entries.get("token_type").toString(); token = tokenType + " " + accessToken; } }else { JSONObject parseObj = getToken(); if (parseObj != null) { Integer expiresIn = parseObj.getInt("expires_in"); if (expiresIn != null) { parseObj.putOpt("time", Instant.now().getEpochSecond()); redisTemplate.opsForHash().putAll("token:his:"+TJ_HOSP_ID, parseObj); redisTemplate.expire("token:his:"+TJ_HOSP_ID, expiresIn - 10, TimeUnit.SECONDS); String accessToken = parseObj.getStr("access_token"); String tokenType = parseObj.getStr("token_type"); token = tokenType + " " + accessToken; } } } if (StrUtil.isNotBlank(token)) syncZd.exec(list, token); } } } src/main/resources/application-win.yaml
@@ -1,6 +1,6 @@ config: path: C:\ltkjprojectconf\config.properties dir: C:\ltkjprojectconf #config: # path: D:\ltkjprojectconf\config.properties # dir: D:\ltkjprojectconf # path: C:\ltkjprojectconf\configregion.properties # dir: C:\ltkjprojectconf config: path: D:\ltkjprojectconf\configregion.properties dir: D:\ltkjprojectconf src/main/resources/mapper/DictHospMapper.xml
@@ -36,6 +36,8 @@ <result property="expirationTime" column="expiration_time" jdbcType="TIMESTAMP"/> <result property="dbname" column="dbname" jdbcType="VARCHAR"/> <result property="beanName" column="bean_name" jdbcType="VARCHAR"/> <result property="isAutoAsyncJg" column="is_auto_async_jg" jdbcType="TINYINT"/> <result property="isTbHisProject" column="is_tb_his_project" jdbcType="TINYINT"/> </resultMap> <sql id="Base_Column_List"> @@ -49,6 +51,6 @@ effective,create_by_name,update_by_name, deleted,create_id,update_id, secret_key,expiration_time,dbname, bean_name,imgBase64 bean_name,imgBase64,is_auto_async_jg,is_tb_his_project </sql> </mapper> src/main/resources/mapper/SqlMapper.xml
New file @@ -0,0 +1,7 @@ <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.SqlMapper"> </mapper>