andy 1 жил өмнө
parent
commit
a16518fd14

+ 3 - 1
src/main/java/com/scbfkj/uni/api/GenericApi.java

@@ -18,6 +18,8 @@ import java.util.Map;
 @RequestMapping("openApi")
 public class GenericApi {
 
+    private static final DataBase DATA_BASE = new DataBase();
+
     @PostMapping({"newdata", "modifydata", "movedata", "query"})
     public ResponseEntity<Map<String, Object>> base(@RequestBody Map<String, Object> body) {
         String uri = RequestUtil.getUri();
@@ -49,7 +51,7 @@ public class GenericApi {
     @PostMapping("*")
     public ResponseEntity<Map<String, Object>> matchService(@RequestBody Map<String, Object> body) throws Exception {
         String uri = RequestUtil.getUri();
-        List<Map<String, Object>> serviceinfoList = DataBase.query(Config.getCenterConnectionStr(), """
+        List<Map<String, Object>> serviceinfoList = DATA_BASE.query(Config.getCenterConnectionStr(), """
                 select serviceid
                 from serviceinfo
                 where urilist like concat('%', ?, '%')""", "/openApi/%s".formatted(uri));

+ 13 - 8
src/main/java/com/scbfkj/uni/api/LogAop.java

@@ -26,6 +26,7 @@ import java.util.concurrent.TimeUnit;
 public class LogAop {
 
     private static final Map<String, RateLimiter> rateLimiterMap = new HashMap<>();
+    private static final DataBase DATA_BASE = new DataBase();
     @Resource
     private SecurityService securityService;
 
@@ -35,6 +36,8 @@ public class LogAop {
 //        请求
         String uri = RequestUtil.getUri();
 
+        System.out.println("请求 url:" + uri);
+
 
 //        请求参数
         Object[] args = joinPoint.getArgs();
@@ -63,20 +66,22 @@ public class LogAop {
                     serviceid = DataAliasGetUtil.getValue("serviceid", map);
                     if (serviceid.isPresent() && uri.startsWith("/openApi")) {
 //                        查找状态
-                        List<Map<String, Object>> mapList = DataBase.query(Config.getCenterConnectionStr(), """
-                                select runstate from servicestate where serviceid=? and containercode = ?""", serviceid.get(), Config.getContainerCode());
-                        if (!mapList.isEmpty()) {
+                        List<Map<String, Object>> mapList = DATA_BASE.query(Config.getCenterConnectionStr(), """
+                                select runstate from servicestate where stoptime is null and  serviceid=? and containercode = ?""", serviceid.get(), Config.getContainerCode());
+                        if (mapList.isEmpty()) {
+                            throw new RuntimeException("服务没有运行或者被熔断");
+                        } else {
                             Map<String, Object> serviceState = mapList.get(0);
                             Object o = serviceState.get("runstate");
 //                            判断服务状态
-                            if (Objects.equals(o, "0")) {
+                            if (Objects.equals(o.toString(), "0")) {
                                 throw new RuntimeException("服务没有运行或者被熔断");
                             }
                         }
                     }
                 }
             }
-            List<Map<String, Object>> ratelimitruleList = DataBase.query(Config.getSecurityConnectionStr(), "select * from ratelimitrule ");
+            List<Map<String, Object>> ratelimitruleList = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from ratelimitrule ");
             Optional<Map<String, Object>> optional = ratelimitruleList.stream().filter(it -> {
                 Object pathMatch = it.get("pathmatch");
                 if (Objects.isNull(pathMatch)) return true;
@@ -101,7 +106,7 @@ public class LogAop {
 
 
             if (Config.isSecurityEnable()) {
-                List<Map<String, Object>> apiInfos = DataBase.query(Config.getSecurityConnectionStr(), "select * from apiinfo");
+                List<Map<String, Object>> apiInfos = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from apiinfo");
 
 
                 Optional<Map<String, Object>> requestpath = apiInfos.stream().filter(it -> {
@@ -126,7 +131,7 @@ public class LogAop {
                                     return ResponseEntity.ok(UniReturnUtil.fail("token验证失败"));
                                 }
                                 if (body != null) {
-                                    List<Map<String, Object>> data = DataBase.query(Config.getSecurityConnectionStr(), "select * from applicationpermissions where appid = ?", RequestUtil.getAppId());
+                                    List<Map<String, Object>> data = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from applicationpermissions where appid = ?", RequestUtil.getAppId());
                                     if (data != null && !data.isEmpty()) {
                                         Map<String, Object> result = data.get(0);
                                         Object columnlist = result.get("columnlist");
@@ -161,7 +166,7 @@ public class LogAop {
                                 }
 
                                 if (body != null && serviceid.isPresent()) {
-                                    List<Map<String, Object>> data = DataBase.query(Config.getSecurityConnectionStr(), "select * from userpermissions where userid = ? and serviceid=?", RequestUtil.getUserId(), serviceid.get());
+                                    List<Map<String, Object>> data = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from userpermissions where userid = ? and serviceid=?", RequestUtil.getUserId(), serviceid.get());
                                     if (data != null && !data.isEmpty()) {
                                         Map<String, Object> result = data.get(0);
                                         Object columnlist = result.get("selectcolumnlist");

+ 2 - 1
src/main/java/com/scbfkj/uni/library/DataAliasGetUtil.java

@@ -11,6 +11,7 @@ import java.util.Optional;
 public class DataAliasGetUtil {
 
 
+    private static final DataBase DATA_BASE = new DataBase();
     private static List<Map<String, Object>> keyAlias = null;
     private static long sequence = 0L;
     private static long lastTimestamp = -1L;
@@ -22,7 +23,7 @@ public class DataAliasGetUtil {
         if (result.isPresent()) return result;
         if (Objects.isNull(keyAlias) || keyAlias.isEmpty()) {
 
-            keyAlias = DataBase.query(Config.getCenterConnectionStr(), """
+            keyAlias = DATA_BASE.query(Config.getCenterConnectionStr(), """
                     select aliasid, keyname, aliasname, aliasdescribe
                     from keyalias""");
 

+ 59 - 27
src/main/java/com/scbfkj/uni/library/RequestUtil.java

@@ -7,54 +7,69 @@ import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
 
 import java.time.LocalDateTime;
+import java.util.Hashtable;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 
-import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;
-
 public class RequestUtil {
     public final static String APP_ID = "appid";
+    private static final DataBase DATABASE = new DataBase();
 
     private RequestUtil() {
     }
 
     public static String getIpAddr() {
-//        请求
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-        HttpServletRequest request = requestAttributes.getRequest();
-        String ip = request.getHeader("x-forwarded-for");
+        String ip = getHeader("x-forwarded-for");
         String unknown = "unknown";
         if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
-            ip = request.getHeader("Proxy-Client-IP");
+            ip = getHeader("Proxy-Client-IP");
         }
         if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
-            ip = request.getHeader("WL-Proxy-Client-IP");
+            ip = getHeader("WL-Proxy-Client-IP");
         }
         if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
-            ip = request.getRemoteAddr();
+            ip = getRemoteAddr();
         }
         return ip;
     }
 
+    private static String getRemoteAddr() {
+        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
+        HttpServletRequest request = requestAttributes.getRequest();
+        return request.getRemoteAddr();
+    }
+
     public static String getAppToken() {
 //        请求
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-        Object appToken = requestAttributes.getRequest().getHeader("token");
+        Object appToken = getHeader("token");
         return Objects.nonNull(appToken) ? appToken.toString() : null;
 
     }
 
     public static String getUserToken() {
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-        Object userToken = requestAttributes.getRequest().getHeader("usertoken");
+        Object userToken = getHeader("usertoken");
         return Objects.nonNull(userToken) ? userToken.toString() : null;
     }
 
+    private static String getHeader(String headerName) {
+        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
+        HttpServletRequest request = requestAttributes.getRequest();
+        return request.getHeader(headerName);
+    }
+
     public static String getAppId() throws Exception {
+        String session = getSessionId();
+        if (session == null) {
+            return null;
+        }
 //        请求
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-        Object appid = requestAttributes.getAttribute(APP_ID, SCOPE_SESSION);
+        Map<String, Object> sessionMap = Config.cache.get(session);
+        if (sessionMap == null) {
+            sessionMap = new Hashtable<>();
+            Config.cache.put(session, sessionMap);
+        }
+        Object appid = sessionMap.get(APP_ID);
         if (Objects.nonNull(appid)) {
             return appid.toString();
         }
@@ -64,19 +79,26 @@ public class RequestUtil {
 
     public static Map<String, Object> getApplication() throws Exception {
 
+        String session = getSessionId();
         String clean = "delete from appconnectlog where expiretime <  ?";
 
 //        清理过期数据
-        DataBase.update(Config.getSecurityConnectionStr(), clean, LocalDateTime.now());
+        DATABASE.update(Config.getSecurityConnectionStr(), clean, LocalDateTime.now());
 //        请求
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-//
-        Object application = requestAttributes.getAttribute("application", SCOPE_SESSION);
+        if (session == null) {
+            return null;
+        }
+        Map<String, Object> sessionMap = Config.cache.get(session);
+        if (sessionMap == null) {
+            sessionMap = new Hashtable<>();
+            Config.cache.put(session, sessionMap);
+        }
+        Object application = sessionMap.get("application");
         if (Objects.isNull(application)) {
             String appToken = getAppToken();
             String requestIp = getIpAddr();
             String query = "select appid from appconnectlog where apptoken=? and requestip =? and expiretime >  ?";
-            List<Map<String, Object>> appConnectLogList = DataBase.query(Config.getSecurityConnectionStr(), query,
+            List<Map<String, Object>> appConnectLogList = DATABASE.query(Config.getSecurityConnectionStr(), query,
                     appToken, requestIp, LocalDateTime.now());
             if (appConnectLogList.isEmpty()) {
                 throw new RuntimeException("当前连接未登录");
@@ -102,12 +124,14 @@ public class RequestUtil {
                            passwordeffective
                     from application
                     where appid = ?""";
-            List<Map<String, Object>> applicationList = DataBase.query(Config.getSecurityConnectionStr(), query, applicationid);
+            List<Map<String, Object>> applicationList = DATABASE.query(Config.getSecurityConnectionStr(), query, applicationid);
             if (applicationList.isEmpty()) {
                 throw new RuntimeException("获取应用失败");
             }
             application = applicationList.get(0);
-            requestAttributes.setAttribute("application", application, SCOPE_SESSION);
+
+            sessionMap.put("application", application);
+
         }
         Map<String, Object> applicationMap = (Map<String, Object>) application;
 
@@ -117,6 +141,7 @@ public class RequestUtil {
     }
 
     public static String getUserId() {
+
 //        请求
         Map<String, Object> userInfo = getUserInfo();
         if (Objects.isNull(userInfo)) {
@@ -128,15 +153,22 @@ public class RequestUtil {
     }
 
     public static Map<String, Object> getUserInfo() {
-//        请求
-        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
-//
-        Object userInfo = requestAttributes.getAttribute("userinfo", SCOPE_SESSION);
+
+        String session = getSessionId();
+        if (session == null) {
+            return null;
+        }
+        Map<String, Object> sessionMap = Config.cache.get(session);
+        if (sessionMap == null) {
+            sessionMap = new Hashtable<>();
+            Config.cache.put(session, sessionMap);
+        }
+        Object userInfo = sessionMap.get("userinfo");
         return Objects.nonNull(userInfo) ? (Map<String, Object>) userInfo : null;
     }
 
     public static String getSessionId() {
-        return RequestContextHolder.currentRequestAttributes().getSessionId();
+        return getHeader("sessionid");
     }
 
     public static String getUri() {

+ 33 - 8
src/main/java/com/scbfkj/uni/library/script/AuthorizationScriptUtil.java

@@ -3,11 +3,13 @@ package com.scbfkj.uni.library.script;
 import com.scbfkj.uni.library.DataFormatUtil;
 import com.scbfkj.uni.library.UniReturnUtil;
 import com.scbfkj.uni.process.DataBase;
+import com.scbfkj.uni.system.Config;
 
 import java.util.*;
 
 public class AuthorizationScriptUtil {
 
+    private static final DataBase DATABASE = new DataBase();
 
     public static Map<String, Object> authorization(String datasourceId, Map<String, Object> data) throws Exception {
 
@@ -31,7 +33,7 @@ public class AuthorizationScriptUtil {
                         from userpermissions
                         where userid=%s and pageconfigurationid=?""".formatted(id);
             }
-            int[] result = DataBase.updateBatch(DatabaseScriptUtil.queryConnectionStr(datasourceId), sql, dataContent.stream().map(it -> new Object[]{it}).toList());
+            int[] result = DATABASE.updateBatch(queryConnectionStr(datasourceId), sql, dataContent.stream().map(it -> new Object[]{it}).toList());
             return UniReturnUtil.success(result);
         } else if (type.equals("2")) {
             Set<Object> childrenGroup = getChildrenGroup(datasourceId, id);
@@ -82,7 +84,7 @@ public class AuthorizationScriptUtil {
                         """;
                 children.put(sql, userInfoValues);
             }
-            DataBase.updateBatchExtend(DatabaseScriptUtil.queryConnectionStr(datasourceId), children);
+            DATABASE.updateBatchExtend(queryConnectionStr(datasourceId), children);
             return UniReturnUtil.success(true);
         }
         return UniReturnUtil.fail("类型错误");
@@ -94,7 +96,7 @@ public class AuthorizationScriptUtil {
         String sql = """
                                 select usergroupid
                 from usergroup where superiorid=?""";
-        List<Map<String, Object>> result = DataBase.query(DatabaseScriptUtil.queryConnectionStr(datasourceId), sql, id);
+        List<Map<String, Object>> result = DATABASE.query(queryConnectionStr(datasourceId), sql, id);
         for (Map<String, Object> it : result) {
             children.addAll(getChildrenGroup(datasourceId, it.get("usergroupid").toString()));
         }
@@ -106,7 +108,7 @@ public class AuthorizationScriptUtil {
         String sql = """
                                 select userid
                 from userinfo where usergroupid=?""";
-        List<Map<String, Object>> result = DataBase.queryBatch(DatabaseScriptUtil.queryConnectionStr(datasourceId), sql, groupIds.stream().map(it -> new Object[]{it}).toList());
+        List<Map<String, Object>> result = DATABASE.queryBatch(queryConnectionStr(datasourceId), sql, groupIds.stream().map(it -> new Object[]{it}).toList());
         for (Map<String, Object> it : result) {
             children.addAll(getChildrenGroup(datasourceId, it.get("userid").toString()));
         }
@@ -125,14 +127,14 @@ public class AuthorizationScriptUtil {
         Object id = value.get("id");
         List<Map<String, Object>> results;
         if (value.get("type").toString().equals("2")) {
-            results = DataBase.query(DatabaseScriptUtil.queryConnectionStr(datasourceId), """
-                    select distinct pageconfiguration.*,selectcolumnlist
+            results = DATABASE.query(queryConnectionStr(datasourceId), """
+                    select distinct pageconfiguration.*,selectcolumnlist,filterset
                     from usergrouppermissions
                              right join pageconfiguration on pageconfiguration.pageconfigurationid = usergrouppermissions.pageconfigurationid
                     where usergroupid = ?""", id);
         } else {
-            results = DataBase.query(DatabaseScriptUtil.queryConnectionStr(datasourceId), """
-                    select  distinct pageconfiguration.*,selectcolumnlist
+            results = DATABASE.query(queryConnectionStr(datasourceId), """
+                    select  distinct pageconfiguration.*,selectcolumnlist,filterset
                     from userpermissions
                         right join pageconfiguration on pageconfiguration.pageconfigurationid = userpermissions.pageconfigurationid  
                     where userid =?""", id);
@@ -140,4 +142,27 @@ public class AuthorizationScriptUtil {
 
         return UniReturnUtil.success(results);
     }
+
+
+    public static String queryConnectionStr(String datasourceId) throws Exception {
+        List<Map<String, Object>> result = DATABASE.query(Config.getCenterConnectionStr(), """
+                select datasourceid,
+                       host,
+                       username,
+                       password,
+                       driverclassname
+                from datasource
+                where datasourceid = ?""", datasourceId);
+        if (result.isEmpty()) {
+            throw new RuntimeException("数据源错误:没有找到数据源");
+        }
+        return DataFormatUtil.toString(result.stream().findFirst().map(it -> {
+            HashMap<String, Object> hashMap = new HashMap<>();
+            hashMap.put("jdbcUrl", it.get("host"));
+            hashMap.put("username", it.get("username"));
+            hashMap.put("password", it.get("password"));
+            hashMap.put("driverClassName", it.get("driverclassname"));
+            return hashMap;
+        }).get());
+    }
 }

+ 49 - 50
src/main/java/com/scbfkj/uni/library/script/DatabaseScriptUtil.java

@@ -17,6 +17,7 @@ public class DatabaseScriptUtil {
     private static final List<String> events = new ArrayList<>();
     private static final Pattern regExpression = Pattern.compile("(?<=《)([^》]+)?(?=》)");//提取书名号变量的正则表达式
     private static final Map<String, List<String>> sqlStrVarList = new HashMap<>();//SQL语句的书名号变量列表
+    private static final DataBase DATABASE = new DataBase();
     public static Map<String, String> sqlStrNewSQL = new HashMap<>();//SQL语句更换书名号变量后的可执行SQL
 
     static {
@@ -28,7 +29,32 @@ public class DatabaseScriptUtil {
         events.add("7");
     }
 
-    public static String getFilterLinesWhereSql(List<Map<String, Object>> filterLines) {
+    public static Pageable pageable(Map<String, Object> args) {
+        Object page = args.get("page");
+        Object size = args.get("size");
+        Long pageNumber = 0L;
+        Long pageSizeNumber = 0L;
+        Object event = args.get("event");
+        if (event == null || !event.toString().equals("0")) {
+            return null;
+        }
+
+        if (Objects.nonNull(page)) {
+            pageNumber = Long.parseLong(page.toString()) - 1;
+        }
+        if (pageNumber < 0) {
+            pageNumber = 0L;
+        }
+        if (Objects.nonNull(size)) {
+            pageSizeNumber = Long.parseLong(size.toString());
+        }
+        if (pageSizeNumber <= 0) {
+            pageSizeNumber = 50L;
+        }
+        return new Pageable(pageNumber, pageSizeNumber);
+    }
+
+    public String getFilterLinesWhereSql(List<Map<String, Object>> filterLines) {
         if (Objects.isNull(filterLines)) filterLines = new ArrayList<>();
         String filterLineWhereStr = null;
         for (Object f : filterLines) {
@@ -38,7 +64,7 @@ public class DatabaseScriptUtil {
         return filterLineWhereStr;
     }
 
-    public static List<String> getSQLVarList(String sqlStr) {
+    public List<String> getSQLVarList(String sqlStr) {
         String newSqlStr = sqlStr;//不破坏之前SQL语句
         List<String> sqlvarList = sqlStrVarList.containsKey(sqlStr) ? sqlStrVarList.get(sqlStr) : new ArrayList<>();//优先从缓存中取
         if (!sqlStrNewSQL.containsKey(sqlStr)) {//缓存不存在则重新获取
@@ -54,13 +80,13 @@ public class DatabaseScriptUtil {
         return sqlvarList;
     }
 
-    private static boolean exists(String connectionStr, String sql, Object[] args) throws Exception {
-        List<Map<String, Object>> mapList = DataBase.queryBatch(connectionStr, sql, Collections.singletonList(args));
+    private boolean exists(String connectionStr, String sql, Object[] args) throws Exception {
+        List<Map<String, Object>> mapList = DATABASE.queryBatch(connectionStr, sql, Collections.singletonList(args));
         if (mapList.isEmpty()) return false;
         return !Objects.equals(mapList.get(0).get("existscount").toString(), "0");
     }
 
-    public static List<Map<String, Object>> query(String connectionStr, String sql, List<Map<String, Object>> argsList, List<String> filterColumns, List<Map<String, Object>> filterLines, Pageable pageable) throws Exception {
+    public List<Map<String, Object>> query(String connectionStr, String sql, List<Map<String, Object>> argsList, List<String> filterColumns, List<Map<String, Object>> filterLines, Pageable pageable) throws Exception {
 
         sql = sql.replaceAll("(\\r)?\\n", " ");
         String filterLineWhereStr = null;
@@ -78,7 +104,7 @@ public class DatabaseScriptUtil {
 
         List<List<Object>> result = new ArrayList<>();
 
-        List<String> names = DatabaseScriptUtil.getSQLVarList(sql);
+        List<String> names = getSQLVarList(sql);
         String newSql = DatabaseScriptUtil.sqlStrNewSQL.get(sql);
 
         if (names.size() == 1 && names.contains("whereStr")) {
@@ -93,7 +119,7 @@ public class DatabaseScriptUtil {
                 }
                 String whereStr = " " + joiner;
                 String sqlStr = sql.replace("《whereStr》", whereStr);
-                List<Map<String, Object>> apply = DataBase.query(connectionStr, sqlStr, args.toArray());
+                List<Map<String, Object>> apply = DATABASE.query(connectionStr, sqlStr, args.toArray());
                 list.addAll(apply);
             }
             return list;
@@ -110,12 +136,11 @@ public class DatabaseScriptUtil {
             if (pageable != null) {
                 newSql = "%s limit %d,%d ".formatted(newSql, pageable.page * pageable.pageSize, pageable.pageSize);
             }
-            return DataBase.queryBatch(connectionStr, newSql, result.stream().map(List::toArray).toList());
+            return DATABASE.queryBatch(connectionStr, newSql, result.stream().map(List::toArray).toList());
         }
     }
 
-
-    public static Map<String, Object> execBySql(String datasourceId, String expression, Map<String, Object> args) throws Exception {
+    public Map<String, Object> execBySql(String datasourceId, String expression, Map<String, Object> args) throws Exception {
         Object event = args.get("event");
         Pageable pageable = pageable(args);
 
@@ -188,7 +213,7 @@ public class DatabaseScriptUtil {
             if (pageable != null && !sql.contains(" limit ")) {
                 sql = "%s limit %d,%d ".formatted(sql, pageable.page * pageable.pageSize, pageable.pageSize);
             }
-            List<Map<String, Object>> queryResult = DataBase.queryBatch(connectionStr, sql, Collections.singletonList(dbFilter.toArray()));
+            List<Map<String, Object>> queryResult = DATABASE.queryBatch(connectionStr, sql, Collections.singletonList(dbFilter.toArray()));
             return UniReturnUtil.success(queryResult);
 
         } else {
@@ -201,7 +226,7 @@ public class DatabaseScriptUtil {
                 }
                 List<String> names = sqlStrVarList.get(expression);
                 String sql = sqlStrNewSQL.get(expression);
-                int[] updateResult = DataBase.updateBatch(connectionStr, sql, dataContent.stream().map(it -> names.stream().map(it::get).toArray()).toList());
+                int[] updateResult = DATABASE.updateBatch(connectionStr, sql, dataContent.stream().map(it -> names.stream().map(it::get).toArray()).toList());
                 return UniReturnUtil.success(updateResult);
             } else {
                 if (sqlStrVarList.containsKey(expression)) {
@@ -209,13 +234,13 @@ public class DatabaseScriptUtil {
                 }
                 List<String> names = sqlStrVarList.get(expression);
                 String sql = " %s  and %s".formatted(sqlStrNewSQL.get(expression), Objects.isNull(filterLineWhereStr) ? " 1=1 " : filterLineWhereStr);
-                int[] updateResult = DataBase.updateBatch(connectionStr, sql, dataContent.stream().map(it -> names.stream().map(it::get).toArray()).toList());
+                int[] updateResult = DATABASE.updateBatch(connectionStr, sql, dataContent.stream().map(it -> names.stream().map(it::get).toArray()).toList());
                 return UniReturnUtil.success(updateResult);
             }
         }
     }
 
-    public static Map<String, Object> execByTableName(String datasourceId, String table, Map<String, Object> args) throws Exception {
+    public Map<String, Object> execByTableName(String datasourceId, String table, Map<String, Object> args) throws Exception {
 
 
         if (Objects.isNull(table) || table.trim().contains(" ")) {
@@ -225,7 +250,6 @@ public class DatabaseScriptUtil {
         Object event = args.get("event");
         Pageable pageable = pageable(args);
 
-
         if (Objects.isNull(event) || !StringUtils.hasText(event.toString())) {
             throw new RuntimeException("执行编号不能为空");
         }
@@ -260,7 +284,7 @@ public class DatabaseScriptUtil {
         List<String> valueNames = null;
         List<String> filterNames = null;
 
-        List<String> allColumns = DataBase.getColumnsByTableName(connectionStr, expression);
+        List<String> allColumns = DATABASE.getColumnsByTableName(connectionStr, expression);
 
 //            查询
         if (Objects.equals("0", event)) {
@@ -328,11 +352,11 @@ public class DatabaseScriptUtil {
             if (pageable != null) {
                 expression = "%s limit %d,%d ".formatted(expression, pageable.page * pageable.pageSize, pageable.pageSize);
             }
-            List<Map<String, Object>> result = DataBase.queryBatch(connectionStr, expression, values);
+            List<Map<String, Object>> result = DATABASE.queryBatch(connectionStr, expression, values);
 
 //            查询关联项
 
-            List<Map<String, Object>> tableJoins = DataBase.query(Config.getCenterConnectionStr(), """
+            List<Map<String, Object>> tableJoins = DATABASE.query(Config.getCenterConnectionStr(), """
                                         select id, sourcetable, targettable, sourcejoincolumn, targetjoincolumn, targetshowcolumns, datasourceid
                     from tablejoin where sourcetable=?""", tableName);
             if (!tableJoins.isEmpty()) {
@@ -360,7 +384,7 @@ public class DatabaseScriptUtil {
                     }
 
 
-                    List<Map<String, Object>> targetDatas = DataBase.query(joinTableConnectionStr, "select * from %s".formatted(targettable));
+                    List<Map<String, Object>> targetDatas = DATABASE.query(joinTableConnectionStr, "select * from %s".formatted(targettable));
 
                     result.forEach(data -> targetDatas
                             .stream()
@@ -483,7 +507,7 @@ public class DatabaseScriptUtil {
                     objects.addAll(valueNames.stream().map(it -> {
 
 //                            新增 更新 对列过滤
-                        if (finalFilterColumns.contains(it) || finalFilterColumns.isEmpty()) {
+                        if (finalFilterColumns.contains(it) || finalFilterColumns.isEmpty() || (finalFilterColumns.get(0).equals("*") && finalFilterColumns.size() == 1)) {
                             return o1.get(it);
                         } else {
                             return null;
@@ -496,21 +520,21 @@ public class DatabaseScriptUtil {
                 }
                 values.add(objects.toArray());
             }
-            int[] ints = DataBase.updateBatch(connectionStr, expression, values);
+            int[] ints = DATABASE.updateBatch(connectionStr, expression, values);
             return UniReturnUtil.success(ints);
         }
     }
 
-    public static Map<String, Object> execByDynamicSql(String datasourceId, String expression, Map<String, Object> args) throws Exception {
+    public Map<String, Object> execByDynamicSql(String datasourceId, String expression, Map<String, Object> args) throws Exception {
         return execBySql(datasourceId, expression, args);
     }
 
-    public static Map<String, Object> execByDynamicTableName(String datasourceId, String table, Map<String, Object> args) throws Exception {
+    public Map<String, Object> execByDynamicTableName(String datasourceId, String table, Map<String, Object> args) throws Exception {
         return execByTableName(datasourceId, table, args);
     }
 
-    public static String queryConnectionStr(String datasourceId) throws Exception {
-        List<Map<String, Object>> result = DataBase.query(Config.getCenterConnectionStr(), """
+    public String queryConnectionStr(String datasourceId) throws Exception {
+        List<Map<String, Object>> result = DATABASE.query(Config.getCenterConnectionStr(), """
                 select datasourceid,
                        host,
                        username,
@@ -531,31 +555,6 @@ public class DatabaseScriptUtil {
         }).get());
     }
 
-    public static Pageable pageable(Map<String, Object> args) {
-        Object page = args.get("page");
-        Object size = args.get("size");
-        Long pageNumber = 0L;
-        Long pageSizeNumber = 0L;
-        Object event = args.get("event");
-        if (event == null || !event.toString().equals("0")) {
-            return null;
-        }
-
-        if (Objects.nonNull(page)) {
-            pageNumber = Long.parseLong(page.toString()) - 1;
-        }
-        if (pageNumber < 0) {
-            pageNumber = 0L;
-        }
-        if (Objects.nonNull(size)) {
-            pageSizeNumber = Long.parseLong(size.toString());
-        }
-        if (pageSizeNumber <= 0) {
-            pageSizeNumber = 50L;
-        }
-        return new Pageable(pageNumber, pageSizeNumber);
-    }
-
     public record Pageable(Long page, Long pageSize) {
     }
 }

+ 1 - 1
src/main/java/com/scbfkj/uni/library/script/JsScriptEngineUtil.java

@@ -57,7 +57,7 @@ public final class JsScriptEngineUtil {
         } catch (Exception e) {
             System.out.println(script);
             e.printStackTrace();
-            throw new RuntimeException(e);
+            throw e;
         } finally {
             if (Objects.nonNull(function)) {
                 scriptPool.returnObject(script, function);

+ 3 - 1
src/main/java/com/scbfkj/uni/library/script/KafkaScriptUtil.java

@@ -11,6 +11,8 @@ import java.util.Map;
 
 public class KafkaScriptUtil {
 
+    private static final DataBase DATA_BASE = new DataBase();
+
     public static Map<String, Object> receptionMessage(String dataSourceId, String topic, String groupId) throws Exception {
 
         return Kafka.receptionMessage(queryConnectionStr(dataSourceId), topic, groupId);
@@ -25,7 +27,7 @@ public class KafkaScriptUtil {
 
 
     private static String queryConnectionStr(String datasourceId) throws Exception {
-        List<Map<String, Object>> result = DataBase.query(Config.getCenterConnectionStr(), """
+        List<Map<String, Object>> result = DATA_BASE.query(Config.getCenterConnectionStr(), """
                 select host
                 from datasource
                 where datasourceid = ?""", datasourceId);

+ 13 - 13
src/main/java/com/scbfkj/uni/process/DataBase.java

@@ -18,7 +18,7 @@ public class DataBase {
     private static final Map<String, List<String>> columns = new HashMap<>();
     private static List<Map<String, Object>> cacheConfigList = new ArrayList<>();
 
-    public static synchronized List<Map<String, Object>> queryBatch(String connectionStr, String sql, List<Object[]> argsList) throws Exception {
+    public List<Map<String, Object>> queryBatch(String connectionStr, String sql, List<Object[]> argsList) throws Exception {
 
 //        缓存数据 connectionStr + sql
 
@@ -61,7 +61,7 @@ public class DataBase {
         return result;
     }
 
-    private static void saveCacheData(String connectionStr, String sql, String key, String effectivedurationColumnName, List<Map<String, Object>> finalResult) {
+    private void saveCacheData(String connectionStr, String sql, String key, String effectivedurationColumnName, List<Map<String, Object>> finalResult) {
         cacheConfigList.stream().filter(it -> Objects.equals(it.get("querysql"), sql) && Objects.equals(it.get("connectset"), connectionStr)).findFirst().ifPresent(it -> {
             Object o = it.get(effectivedurationColumnName);
             LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(Long.parseLong(o.toString()));
@@ -72,7 +72,7 @@ public class DataBase {
         });
     }
 
-    public static List<Map<String, Object>> query(String connectionStr, String sql, Object... args) throws Exception {
+    public List<Map<String, Object>> query(String connectionStr, String sql, Object... args) throws Exception {
 
 //        缓存数据 connectionStr + sql
 
@@ -115,7 +115,7 @@ public class DataBase {
         return result;
     }
 
-    public static int[] updateBatch(String connectionStr, String sql, List<Object[]> argsList) throws Exception {
+    public int[] updateBatch(String connectionStr, String sql, List<Object[]> argsList) throws Exception {
         HikariPool dataSourcePool = getDataSourcePool(connectionStr);
         if (sql.trim().startsWith("insert")) {
             try (Connection connection = dataSourcePool.getConnection();
@@ -174,7 +174,7 @@ public class DataBase {
         }
     }
 
-    public static Map<String, int[]> updateBatchExtend(String connectionStr, Map<String, List<Object[]>> datas) throws Exception {
+    public Map<String, int[]> updateBatchExtend(String connectionStr, Map<String, List<Object[]>> datas) throws Exception {
         HikariPool dataSourcePool = getDataSourcePool(connectionStr);
         try (Connection connection = dataSourcePool.getConnection()) {
 
@@ -208,7 +208,7 @@ public class DataBase {
         }
     }
 
-    public static boolean exec(String connectionStr, String sql) throws Exception {
+    public boolean exec(String connectionStr, String sql) throws Exception {
         HikariPool dataSourcePool = getDataSourcePool(connectionStr);
         try (Connection connection = dataSourcePool.getConnection();
              PreparedStatement preparedStatement = connection.prepareStatement(sql)
@@ -225,7 +225,7 @@ public class DataBase {
         }
     }
 
-    public static int update(String connectionStr, String sql, Object... args) throws Exception {
+    public int update(String connectionStr, String sql, Object... args) throws Exception {
 
         if (sql.trim().startsWith("insert")) {
             return insertReturnKeys(connectionStr, sql, args);
@@ -244,7 +244,7 @@ public class DataBase {
         }
     }
 
-    public static int insertReturnKeys(String connectionStr, String sql, Object... args) throws Exception {
+    public int insertReturnKeys(String connectionStr, String sql, Object... args) throws Exception {
         HikariPool dataSourcePool = getDataSourcePool(connectionStr);
         try (Connection connection = dataSourcePool.getConnection();
              PreparedStatement preparedStatement = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)
@@ -263,7 +263,7 @@ public class DataBase {
         }
     }
 
-    public static HikariPool getDataSourcePool(String connectionStr) throws Exception {
+    public HikariPool getDataSourcePool(String connectionStr) throws Exception {
         if (dataSourcePools.containsKey(connectionStr)) {
             return dataSourcePools.get(connectionStr);
         }
@@ -278,7 +278,7 @@ public class DataBase {
         return dataSourcePool;
     }
 
-    private static HikariPool createDataSourcePool(@Nonnull String url, String username, String password, String driver, String poolName) throws Exception {
+    private HikariPool createDataSourcePool(@Nonnull String url, String username, String password, String driver, String poolName) throws Exception {
         HikariConfig hikariConfig = new HikariConfig();
         hikariConfig.setMaximumPoolSize(Math.min(Runtime.getRuntime().availableProcessors(), 8));//最大核心数:当前可用CPU数,最大16
         hikariConfig.setKeepaliveTime(60000); //用于跟数据库保持心跳连接
@@ -313,7 +313,7 @@ public class DataBase {
         return new HikariPool(hikariConfig);
     }
 
-    public static List<String> getColumns(String connection, String sql, ResultSet resultSet) throws SQLException {
+    public List<String> getColumns(String connection, String sql, ResultSet resultSet) throws SQLException {
         if (columns.containsKey(connection + sql)) {
             return columns.get(connection + sql);
         }
@@ -326,7 +326,7 @@ public class DataBase {
         return names;
     }
 
-    public static List<String> getColumnsByTableName(String connection, String tableName) throws SQLException {
+    public List<String> getColumnsByTableName(String connection, String tableName) throws SQLException {
         if (columns.containsKey(connection + tableName)) {
             return columns.get(connection + tableName);
         }
@@ -346,7 +346,7 @@ public class DataBase {
         return names;
     }
 
-    public static List<Map<String, Object>> getResult(String connection, String sql, ResultSet resultSet) throws SQLException {
+    public List<Map<String, Object>> getResult(String connection, String sql, ResultSet resultSet) throws SQLException {
         List<String> cs = getColumns(connection, sql, resultSet);
         List<Map<String, Object>> result = new ArrayList<>();
         while (resultSet.next()) {

+ 12 - 10
src/main/java/com/scbfkj/uni/service/ControlService.java

@@ -22,12 +22,14 @@ public class ControlService {
     private final static String SERVICE_ID = "serviceid";
     private final static String CODE = "code";
 
+    private static final DataBase DATA_BASE = new DataBase();
+
     public static Map<String, Object> stopServiceByContainerCode(String containerCode) {
 
 //        查询服务类型为主动采集的服务
 
         try {
-            List<Map<String, Object>> serviceInfos = DataBase.query(Config.getCenterConnectionStr(), SERVICEINFO_WHERE_CONTAINERCODE, containerCode);
+            List<Map<String, Object>> serviceInfos = DATA_BASE.query(Config.getCenterConnectionStr(), SERVICEINFO_WHERE_CONTAINERCODE, containerCode);
 //        循环启动
 
             Map<String, List<Map<String, Object>>> results = serviceInfos.stream()
@@ -43,7 +45,7 @@ public class ControlService {
 
 //        查询服务类型为主动采集的服务
         try {
-            List<Map<String, Object>> serviceInfos = DataBase.query(Config.getCenterConnectionStr(), SERVICEINFO_WHERE_CONTAINERCODE, containerCode);
+            List<Map<String, Object>> serviceInfos = DATA_BASE.query(Config.getCenterConnectionStr(), SERVICEINFO_WHERE_CONTAINERCODE, containerCode);
             Map<String, List<Map<String, Object>>> results = serviceInfos.stream()
                     .map(it -> start(it.get(SERVICE_ID).toString(), containerCode))
                     .collect(Collectors.groupingBy(it -> it.get(CODE).toString()));
@@ -61,7 +63,7 @@ public class ControlService {
      */
     public static Map<String, Object> start(String serviceId, String containerCode) {
         try {
-            List<Map<String, Object>> serviceInfoList = DataBase.query(Config.getCenterConnectionStr(), "select tasktype from serviceinfo where serviceid=?", serviceId);
+            List<Map<String, Object>> serviceInfoList = DATA_BASE.query(Config.getCenterConnectionStr(), "select tasktype from serviceinfo where serviceid=?", serviceId);
 
             if (serviceInfoList.isEmpty()) {
                 return UniReturnUtil.fail("服务%s没有配置".formatted(serviceId));
@@ -110,32 +112,32 @@ public class ControlService {
     private static void updateServiceState(String serviceId, String containerCode, String state) throws Exception {
         if (Objects.equals(state, "1")) {
 
-            List<Map<String, Object>> mapList = DataBase.query(Config.getCenterConnectionStr(), "select runstate,servicestateid from servicestate where stoptime is  null and  serviceid=? and containercode=?", serviceId, containerCode);
+            List<Map<String, Object>> mapList = DATA_BASE.query(Config.getCenterConnectionStr(), "select runstate,servicestateid from servicestate where stoptime is  null and  serviceid=? and containercode=?", serviceId, containerCode);
             if (mapList.isEmpty()) {
 
-                List<Map<String, Object>> result = DataBase.query(Config.getCenterConnectionStr(), "select servicename from serviceinfo where serviceid=?", serviceId);
+                List<Map<String, Object>> result = DATA_BASE.query(Config.getCenterConnectionStr(), "select servicename from serviceinfo where serviceid=?", serviceId);
                 Object servicename = result.isEmpty() ? null : result.get(0).get("servicename");
-                result = DataBase.query(Config.getCenterConnectionStr(), "select containerid from container where containercode=?", containerCode);
+                result = DATA_BASE.query(Config.getCenterConnectionStr(), "select containerid from container where containercode=?", containerCode);
                 Object containerid = result.isEmpty() ? null : result.get(0).get("containerid");
 
-                DataBase.update(Config.getCenterConnectionStr(), "insert into  servicestate(serviceid,starttime,containercode,runstate,workpath,servicename,containerid) values (?,?,?,'1',?,?,?)",
+                DATA_BASE.update(Config.getCenterConnectionStr(), "insert into  servicestate(serviceid,starttime,containercode,runstate,workpath,servicename,containerid) values (?,?,?,'1',?,?,?)",
                         serviceId,
                         DataFormatUtil.toString(LocalDateTime.now()),
                         containerCode,
                         new File(".").getAbsolutePath(), servicename, containerid);
             } else {
                 String serviceStateId = mapList.get(0).get("servicestateid").toString();
-                DataBase.update(Config.getCenterConnectionStr(), "update servicestate set starttime=?,runstate='1',workpath = ? where  servicestateid = ? and containercode =?",
+                DATA_BASE.update(Config.getCenterConnectionStr(), "update servicestate set starttime=?,runstate='1',workpath = ? where  servicestateid = ? and containercode =?",
                         DataFormatUtil.toString(LocalDateTime.now()),
                         new File(".").getAbsolutePath(),
                         serviceStateId, containerCode);
             }
         } else {
-            List<Map<String, Object>> mapList = DataBase.query(Config.getCenterConnectionStr(), "select servicestateid, runstate from servicestate where stoptime is  null and  serviceid=? and containercode=? order by servicestateid desc", serviceId, containerCode);
+            List<Map<String, Object>> mapList = DATA_BASE.query(Config.getCenterConnectionStr(), "select servicestateid, runstate from servicestate where stoptime is  null and  serviceid=? and containercode=? order by servicestateid desc", serviceId, containerCode);
 
             if (!mapList.isEmpty()) {
                 String serviceStateId = mapList.get(0).get("servicestateid").toString();
-                DataBase.update(Config.getCenterConnectionStr(), "update servicestate set stoptime=?,runstate='0' where  servicestateid = ? and containercode =?",
+                DATA_BASE.update(Config.getCenterConnectionStr(), "update servicestate set stoptime=?,runstate='0' where  servicestateid = ? and containercode =?",
                         DataFormatUtil.toString(LocalDateTime.now()),
                         serviceStateId, containerCode);
             }

+ 11 - 9
src/main/java/com/scbfkj/uni/service/DataProcessService.java

@@ -21,6 +21,8 @@ import java.util.concurrent.Executors;
 
 public class DataProcessService {
 
+    private static final DataBase DATA_BASE = new DataBase();
+    private static final DatabaseScriptUtil DATABASE_SCRIPT_UTIL = new DatabaseScriptUtil();
     //    添加一个线程池
 // 创建一个固定大小的线程池,包含2个线程
     private static final ExecutorService executor = Executors.newWorkStealingPool();
@@ -47,14 +49,14 @@ public class DataProcessService {
 
 //        熔断
 //            查询服务运行状态
-            List<Map<String, Object>> serviceState = DataBase.query(Config.getCenterConnectionStr(), """
+            List<Map<String, Object>> serviceState = DATA_BASE.query(Config.getCenterConnectionStr(), """
                     select  runstate
                     from servicestate
                     where serviceid =? and runstate = '1' and containercode=? order by servicestateid desc""", serviceId, Config.getContainerCode());
             if (serviceState.isEmpty() || serviceState.get(0).get("runstate").equals("0")) {
                 throw new RuntimeException("服务没有运行");
             }
-            List<Map<String, Object>> serviceInfoList = DataBase.query(Config.getCenterConnectionStr(), """
+            List<Map<String, Object>> serviceInfoList = DATA_BASE.query(Config.getCenterConnectionStr(), """
                     select serviceid,
                                                servicename,
                                                servicetype,
@@ -84,7 +86,7 @@ public class DataProcessService {
             }
             HashMap<String, Object> source = new HashMap<>();
 
-            List<Map<String, Object>> algorithmLibraries = DataBase.query(Config.getCenterConnectionStr(), """
+            List<Map<String, Object>> algorithmLibraries = DATA_BASE.query(Config.getCenterConnectionStr(), """
                     select algorithmlibraryid,
                            serviceid,
                            algorithmtype,
@@ -159,9 +161,9 @@ public class DataProcessService {
                 resource.add(data);
                 Object parameterSet = algorithmLibrary.get("parameterset");
                 Object dataSourceId = algorithmLibrary.get("datasourceid");
-                List<Map<String, Object>> datasourceList = DataBase.query(Config.getCenterConnectionStr(), "select * from datasource where datasourceid=?", dataSourceId);
+                List<Map<String, Object>> datasourceList = DATA_BASE.query(Config.getCenterConnectionStr(), "select * from datasource where datasourceid=?", dataSourceId);
                 Map<String, Object> datasource = datasourceList.isEmpty() ? null : datasourceList.get(0);
-                List<Map<String, Object>> params = DataBase.query(Config.getCenterConnectionStr(), """
+                List<Map<String, Object>> params = DATA_BASE.query(Config.getCenterConnectionStr(), """
                         select
                         algorithmparametersid, algorithmlibraryid, parametername, subscriptionexpressions, parametertype, datasource
                         from algorithmparameters where algorithmlibraryid =?""", algorithmlibraryid.toString());
@@ -234,7 +236,7 @@ public class DataProcessService {
                 Object algorithmsourcelibraryid = algorithmLibrary.get("algorithmsourcelibraryid");
                 if (Objects.nonNull(algorithmsourcelibraryid) && algorithmsourcelibraryid.toString().trim().length() > 0) {
 
-                    List<Map<String, Object>> algorithmsourcelibraryList = DataBase.query(Config.getCenterConnectionStr(), "select * from algorithmsourcelibrary where id=? ", algorithmsourcelibraryid);
+                    List<Map<String, Object>> algorithmsourcelibraryList = DATA_BASE.query(Config.getCenterConnectionStr(), "select * from algorithmsourcelibrary where id=? ", algorithmsourcelibraryid);
                     Map<String, Object> algorithmsourcelibrary = algorithmsourcelibraryList.get(0);
 
                     HashMap<String, Object> configMap = new HashMap<>();
@@ -318,7 +320,7 @@ public class DataProcessService {
             String finalServiceId1 = serviceId;
             executor.execute(() -> {
                 try {
-                    DataBase.update(Config.getCenterConnectionStr(), """
+                    DATA_BASE.update(Config.getCenterConnectionStr(), """
                             update servicestate
                             set lasttime = ?,workpath = ?
                             where serviceid=? and containercode=?""", LocalDateTime.now(), new File(".").getAbsolutePath(), finalServiceId1, Config.getContainerCode());
@@ -357,9 +359,9 @@ public class DataProcessService {
                 expression = expression.replaceAll("\\s*(\\r)?\\n\\s*", " ").trim();
                 boolean isTableName = !expression.contains(" ");
                 if (isTableName) {
-                    return DatabaseScriptUtil.execByTableName(DataFormatUtil.toString(parameters.get(0)), expression, (Map<String, Object>) parameters.get(2));
+                    return DATABASE_SCRIPT_UTIL.execByTableName(DataFormatUtil.toString(parameters.get(0)), expression, (Map<String, Object>) parameters.get(2));
                 } else {
-                    return DatabaseScriptUtil.execBySql(DataFormatUtil.toString(parameters.get(0)), expression, (Map<String, Object>) parameters.get(2));
+                    return DATABASE_SCRIPT_UTIL.execBySql(DataFormatUtil.toString(parameters.get(0)), expression, (Map<String, Object>) parameters.get(2));
                 }
             }
             default -> {

+ 28 - 9
src/main/java/com/scbfkj/uni/service/LoggerService.java

@@ -18,6 +18,7 @@ import java.util.stream.Stream;
 
 public class LoggerService {
 
+    private static final DataBase DATA_BASE = new DataBase();
     private static final String CONNECTION = """
             {
               "jdbcUrl": "jdbc:sqlite:%s",
@@ -38,7 +39,7 @@ public class LoggerService {
             if (!fileNames.contains(filename)) {
                 if (!new File(filePath).exists()) {
                     try {
-                        DataBase.exec(connectionStr, """
+                        DATA_BASE.exec(connectionStr, """
                                 create table logs
                                 (
                                     logid         Integer
@@ -59,11 +60,11 @@ public class LoggerService {
         }
         try {
             List<Object[]> datas = new ArrayList<>();
-            List<Map<String, Object>> targets = DataBase.query(Config.getCenterConnectionStr(), "select * from systeminfo where keyname=?", type.getName());
+            List<Map<String, Object>> targets = DATA_BASE.query(Config.getCenterConnectionStr(), "select * from systeminfo where keyname=?", type.getName());
             for (Map<String, Object> targetconnection : targets) {
                 datas.add(new Object[]{type.getName(), filePath, targetconnection.get("datasourceid"), targetconnection.get("expression"), DataFormatUtil.toString(data)});
             }
-            DataBase.updateBatch(connectionStr, "insert into logs (target,currentfile,datasourceid,expression,datacontent) values(?,?,?,?,?)", datas);
+            DATA_BASE.updateBatch(connectionStr, "insert into logs (target,currentfile,datasourceid,expression,datacontent) values(?,?,?,?,?)", datas);
         } catch (Exception e) {
             System.out.println(UniReturnUtil.getMessage(e));
         }
@@ -88,7 +89,7 @@ public class LoggerService {
                 }).flatMap(connectionStr -> {
 //                    查询数据
                     try {
-                        return DataBase.query(connectionStr, "select logid, target, currentfile, datasourceid, expression, datacontent from logs ").stream();
+                        return DATA_BASE.query(connectionStr, "select logid, target, currentfile, datasourceid, expression, datacontent from logs ").stream();
                     } catch (Exception e) {
                         Matcher matcher = Pattern.compile("logs/\\d+\\.sqlite").matcher(connectionStr);
                         if (matcher.find()) {
@@ -116,26 +117,44 @@ public class LoggerService {
 
 //                        解析发送目标连接字符串
                         try {
-                            List<Map<String, Object>> dataSourceList = DataBase.query(Config.getCenterConnectionStr(), "select   connectset, datasourcetype from datasource where datasourceid=?", datasourceid);
+                            List<Map<String, Object>> dataSourceList = DATA_BASE.query(Config.getCenterConnectionStr(), "select   * from datasource where datasourceid=?", datasourceid);
                             if (dataSourceList.isEmpty()) {
                                 return;
                             }
                             Map<String, Object> config = dataSourceList.get(0);
                             String type = config.getOrDefault("datasourcetype", "DB").toString();
-                            String connectionStr = config.get("connectset").toString();
-                            String expression = value1.get(0).get("expression").toString();
+                            String connectionStr;
                             List<Object> parameters = new ArrayList<>();
 
                             switch (type.toUpperCase()) {
                                 case "KAFKA" -> {
+                                    connectionStr = DataFormatUtil.toString(dataSourceList.stream().findFirst().map(it -> {
+                                        HashMap<String, Object> hashMap = new HashMap<>();
+                                        hashMap.put("bootstrap.servers", it.get("host"));
+                                        return hashMap;
+                                    }).get());
                                     List<Object> datas = datacontentStream.map(Object.class::cast).toList();
                                     Kafka.sendMessage(connectionStr, targetName, datas);
                                 }
                                 case "ES" -> {
+                                    connectionStr = DataFormatUtil.toString(dataSourceList.stream().findFirst().map(it -> {
+                                        HashMap<String, Object> hashMap = new HashMap<>();
+                                        hashMap.put("host", it.get("host"));
+                                        return hashMap;
+                                    }).get());
                                     List<String> datas = datacontentStream.toList();
                                     Elasticsearch.exec(connectionStr, targetName, "CREATE", datas);
                                 }
                                 case "DB" -> {
+
+                                    connectionStr = DataFormatUtil.toString(dataSourceList.stream().findFirst().map(it -> {
+                                        HashMap<String, Object> hashMap = new HashMap<>();
+                                        hashMap.put("jdbcUrl", it.get("host"));
+                                        hashMap.put("username", it.get("username"));
+                                        hashMap.put("password", it.get("password"));
+                                        hashMap.put("driverClassName", it.get("driverclassname"));
+                                        return hashMap;
+                                    }).get());
                                     parameters.add(connectionStr);
                                     parameters.add(targetName);
                                     parameters.add(new HashMap<>() {{
@@ -156,7 +175,7 @@ public class LoggerService {
                         if (!errorFileNames.contains(it)) {
                             String connectionStr = CONNECTION.formatted(it);
                             try {
-                                DataBase.exec(connectionStr, """
+                                DATA_BASE.exec(connectionStr, """
                                         delete
                                          from logs
                                          where 1=1""");
@@ -175,7 +194,7 @@ public class LoggerService {
         logsFiles.stream().filter(f -> errorFileNames.stream().filter(Objects::nonNull).noneMatch(errorFileName -> errorFileName.contains(f.getName()))).forEach(f -> {
             String connectionStr = CONNECTION.formatted(DIR + f.getName());
             try {
-                DataBase.update(connectionStr, "delete  from logs");
+                DATA_BASE.update(connectionStr, "delete  from logs");
                 HikariPool hikariPool = DataBase.dataSourcePools.remove(connectionStr);
                 if (Objects.nonNull(hikariPool)) hikariPool.shutdown();
 //                删除文件一直不成功 怀疑是数据库连接导致文件被使用导致一直删除不成功

+ 66 - 52
src/main/java/com/scbfkj/uni/service/SecurityService.java

@@ -5,21 +5,18 @@ import com.scbfkj.uni.process.DataBase;
 import com.scbfkj.uni.system.Config;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
 
 import java.security.SecureRandom;
 import java.time.LocalDateTime;
 import java.util.*;
 
 import static com.scbfkj.uni.library.DataAliasGetUtil.getValue;
-import static org.springframework.web.context.request.RequestAttributes.SCOPE_REQUEST;
-import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;
 
 @Service
 public class SecurityService {
 
     private static final SecureRandom RANDOM = new SecureRandom();
+    private static final DataBase DATABASE = new DataBase();
     @Value("${app.token-effective:604800}")
     private long defaultAppTokenEffective;
     @Value("${app.code-effective:600}")
@@ -45,7 +42,7 @@ public class SecurityService {
         Optional<String> appSecret = getValue("appsecret", requestData);
         if (appSecret.isPresent() && appid.isPresent()) {
             String clean = "delete from appconnectlog where expiretime < ? ";
-            DataBase.update(Config.getSecurityConnectionStr(), clean, LocalDateTime.now());
+            DATABASE.update(Config.getSecurityConnectionStr(), clean, LocalDateTime.now());
             String query = """
                                 select applicationid,
                            appid,
@@ -64,7 +61,7 @@ public class SecurityService {
                            passwordeffective
                     from application
                      where appid = ? and appsecret = ?""";
-            List<Map<String, Object>> applicationList = DataBase.query(Config.getSecurityConnectionStr(), query, appid.get(), appSecret.get());
+            List<Map<String, Object>> applicationList = DATABASE.query(Config.getSecurityConnectionStr(), query, appid.get(), appSecret.get());
 
             if (applicationList.isEmpty()) {
                 throw new RuntimeException("appid 或 appsecret 错误");
@@ -79,11 +76,11 @@ public class SecurityService {
             }
             LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(apptokeneffective);
             String ip = RequestUtil.getIpAddr();
-            List<Map<String, Object>> logs = DataBase.query(Config.getSecurityConnectionStr(), "select connid,  apptoken, expiretime, lasttime from appconnectlog where requestip=? and appid = ?", ip, appid.get());
+            List<Map<String, Object>> logs = DATABASE.query(Config.getSecurityConnectionStr(), "select connid,  apptoken, expiretime, lasttime from appconnectlog where requestip=? and appid = ?", ip, appid.get());
             String appToken;
             if (!logs.isEmpty()) {
                 Map<String, Object> applicationlog = logs.get(0);
-                DataBase.update(Config.getSecurityConnectionStr(), """
+                DATABASE.update(Config.getSecurityConnectionStr(), """
                                                 update appconnectlog
                         set expiretime = ?,lasttime=?
                         where connid=?""", expiresTime, LocalDateTime.now(), applicationlog.get("connid"));
@@ -92,16 +89,24 @@ public class SecurityService {
                 String sessionId = RequestUtil.getSessionId();
                 appToken = DataEncryptionUtil.signatureMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
 
-                DataBase.update(Config.getSecurityConnectionStr(), """
+                DATABASE.update(Config.getSecurityConnectionStr(), """
                                                 insert into appconnectlog (appid, requesttime, requestip, apptoken, expiretime, lasttime)
                         values (?,?,?,?,?,?)""", appid.get(), LocalDateTime.now(), ip, appToken, expiresTime, LocalDateTime.now());
             }
 //            添加token和过期时间
             application.put("token", appToken);
             application.put("expirestime", DataFormatUtil.toString(expiresTime));
-            RequestContextHolder.currentRequestAttributes().setAttribute("application", application, SCOPE_SESSION);
+
 //            清理敏感信息 appsecret
             application.put("appsecret", null);
+
+            long currentTimeMillis = System.currentTimeMillis();
+            long l = currentTimeMillis << 4;
+
+            String string = DataEncryptionUtil.signatureMD5(String.valueOf(l));
+            application.put("sessionid", string);
+            Map<String, Object> sessionMap = Config.cache.computeIfAbsent(string, k -> new Hashtable<>());
+            sessionMap.put("application", application);
             return UniReturnUtil.success(application);
         }
         return UniReturnUtil.fail("appid 或 appsecret 不能为空");
@@ -112,8 +117,8 @@ public class SecurityService {
 
     public Map<String, Object> refreshToken() throws Exception {
 
-        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
-        Object appid = requestAttributes.getAttribute("appid", SCOPE_REQUEST);
+        Object appid = RequestUtil.getAppId();
+
 
         Map<String, Object> application = RequestUtil.getApplication();
 
@@ -128,7 +133,7 @@ public class SecurityService {
         Map<String, Object> data = new HashMap<>();
         try {
             String update = "update appconnectlog set expiretime=? where apptoken =? and requestip =? and appid=?";
-            int updateRow = DataBase.update(Config.getSecurityConnectionStr(), update, expiresTime, appToken, RequestUtil.getIpAddr(), appid);
+            int updateRow = DATABASE.update(Config.getSecurityConnectionStr(), update, expiresTime, appToken, RequestUtil.getIpAddr(), appid);
 
             if (updateRow > 0) {
                 data.put("expirestime", DataFormatUtil.toString(expiresTime));
@@ -244,7 +249,7 @@ public class SecurityService {
                        isdelete
                 from userinfo
                      where  account =?""";
-        List<Map<String, Object>> userInfoList = DataBase.query(Config.getSecurityConnectionStr(), query, username.get());
+        List<Map<String, Object>> userInfoList = DATABASE.query(Config.getSecurityConnectionStr(), query, username.get());
 
         Map<String, Object> userInfo;
         if (userInfoList.isEmpty()) {
@@ -262,7 +267,13 @@ public class SecurityService {
             }
         }
         Object userId = userInfo.get("userid");
-        RequestContextHolder.currentRequestAttributes().setAttribute("userinfo", userInfo, SCOPE_SESSION);
+
+        Map<String, Object> sessionMap = Config.cache.get(sessionId);
+        if (sessionMap == null) {
+            sessionMap = new Hashtable<>();
+            Config.cache.put(sessionId, sessionMap);
+        }
+        sessionMap.put("userinfo", userInfo);
         String query1 = """
                 select loginid,
                        userid,
@@ -278,20 +289,20 @@ public class SecurityService {
                        appid
                 from userloginlog                 
                     where userid = ? and isexpires = 0 and logouttime is null""";
-        List<Map<String, Object>> userLoginLogList = DataBase.query(Config.getSecurityConnectionStr(), query1, userInfo.get("userid"));
+        List<Map<String, Object>> userLoginLogList = DATABASE.query(Config.getSecurityConnectionStr(), query1, userInfo.get("userid"));
 
         Map<String, Object> data = new HashMap<>();
         String appToken = RequestUtil.getAppToken();
         String insert = "insert into userloginlog ( userid, requestip, sessionid, logintime, usertoken, lasttime, lastheartbeat,apptoken,isexpires,appid)values (?,?,?,?,?,?,?,?,0,?)";
         if (userLoginLogList.isEmpty()) {
             data.put("userstatus", "0");
-            DataBase.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
+            DATABASE.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
         } else {
             Object multilogin = application.get("multilogin");
             if (Objects.equals(DataFormatUtil.toString(multilogin), "1")) {
                 Optional<Map<String, Object>> log = userLoginLogList.stream().filter(it -> it.get("sessionid").equals(sessionId)).findAny();
                 if (log.isEmpty()) {
-                    DataBase.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
+                    DATABASE.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
 //                } else {
 //                    Map<String, Object> map = log.get();
 //                    if (Objects.isNull(map.get("apptoken"))) {
@@ -305,7 +316,7 @@ public class SecurityService {
                 Optional<Map<String, Object>> log = userLoginLogList.stream().filter(it -> it.get("sessionid").equals(sessionId)).findAny();
                 if (log.isEmpty()) {
 
-                    DataBase.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
+                    DATABASE.update(Config.getSecurityConnectionStr(), insert, userId, ip, sessionId, LocalDateTime.now(), null, LocalDateTime.now(), LocalDateTime.now(), appToken, appId);
                 }
                 data.put("userstatus", "1");
             }
@@ -323,6 +334,9 @@ public class SecurityService {
         String appToken = RequestUtil.getAppToken();
         String ip = RequestUtil.getIpAddr();
         String sessionId = RequestUtil.getSessionId();
+        if (sessionId == null) {
+            return UniReturnUtil.fail("sessionid 不匹配");
+        }
         String query = """
                 select loginid,
                        userid,
@@ -338,14 +352,14 @@ public class SecurityService {
                        appid
                 from userloginlog
                      where apptoken=? and sessionid=? and requestip=? and isexpires=0 and logouttime is null """;
-        List<Map<String, Object>> userLoginLogList = DataBase.query(Config.getSecurityConnectionStr(), query, appToken, sessionId, ip);
+        List<Map<String, Object>> userLoginLogList = DATABASE.query(Config.getSecurityConnectionStr(), query, appToken, sessionId, ip);
         if (userLoginLogList.isEmpty()) {
             return UniReturnUtil.fail("登录失败:在数据库中没有找到当前session的登录请求");
         }
         Map<String, Object> userLoginLog = userLoginLogList.get(0);
         String userToken = DataEncryptionUtil.signatureMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
         String update = "update userloginlog set apptoken=null,usertoken=?,lasttime=? where  loginid=?";
-        DataBase.update(Config.getSecurityConnectionStr(), update, userToken, LocalDateTime.now(), userLoginLog.get("loginid"));
+        DATABASE.update(Config.getSecurityConnectionStr(), update, userToken, LocalDateTime.now(), userLoginLog.get("loginid"));
         HashMap<String, Object> data = new HashMap<>();
         data.put("usertoken", userToken);
 
@@ -368,26 +382,26 @@ public class SecurityService {
                        isexpires,
                        appid
                 from userloginlog
-                                 where isexpires = 0 and usertoken = ? and sessionid = ?""";
-        List<Map<String, Object>> userLoginLogList = DataBase.query(Config.getSecurityConnectionStr(), query, userToken, sessionId);
-        if (userLoginLogList.isEmpty()) {
-            return UniReturnUtil.fail("用户登录查询失败");
-        }
-        Map<String, Object> userLoginLog = userLoginLogList.get(0);
-        Object lastheartbeat = userLoginLog.get("lastheartbeat");
-        LocalDateTime dateTime = DataFormatUtil.toDateTime(lastheartbeat);
-        if (Objects.nonNull(dateTime)) {
-            Map<String, Object> application = RequestUtil.getApplication();
-            Object apptokeneffectiveObj = application.get("apptokeneffective");
-            Long apptokeneffective = defaultAppTokenEffective;
-            if (Objects.nonNull(apptokeneffectiveObj)) {
-                apptokeneffective = Long.parseLong(apptokeneffectiveObj.toString());
-            }
-
-            if (dateTime.plusSeconds(apptokeneffective).isAfter(LocalDateTime.now())) {
-                return UniReturnUtil.success(null);
-            }
+                                 where logouttime is null and usertoken = ? and sessionid = ?""";
+        List<Map<String, Object>> userLoginLogList = DATABASE.query(Config.getSecurityConnectionStr(), query, userToken, sessionId);
+        if (!userLoginLogList.isEmpty()) {
+            return UniReturnUtil.success(null);
         }
+//        Map<String, Object> userLoginLog = userLoginLogList.get(0);
+//        Object lastheartbeat = userLoginLog.get("lastheartbeat");
+//        LocalDateTime dateTime = DataFormatUtil.toDateTime(lastheartbeat);
+//        if (Objects.nonNull(dateTime)) {
+//            Map<String, Object> application = RequestUtil.getApplication();
+//            Object apptokeneffectiveObj = application.get("apptokeneffective");
+//            Long apptokeneffective = defaultAppTokenEffective;
+//            if (Objects.nonNull(apptokeneffectiveObj)) {
+//                apptokeneffective = Long.parseLong(apptokeneffectiveObj.toString());
+//            }
+//
+//            if (dateTime.plusSeconds(apptokeneffective).isAfter(LocalDateTime.now())) {
+//                return UniReturnUtil.success(null);
+//            }
+//        }
         return UniReturnUtil.fail("用户token已过期");
 
     }
@@ -411,9 +425,9 @@ public class SecurityService {
                        isexpires,
                        appid
                 from userloginlog
-                                 where isexpires=0 and usertoken=? and sessionid=?""";
+                                 where logouttime is null and usertoken=? and sessionid=?""";
 
-        List<Map<String, Object>> userLoginLogList = DataBase.query(Config.getSecurityConnectionStr(), query, userToken, sessionId);
+        List<Map<String, Object>> userLoginLogList = DATABASE.query(Config.getSecurityConnectionStr(), query, userToken, sessionId);
 
         if (userLoginLogList.isEmpty()) {
             return UniReturnUtil.fail("登出失败");
@@ -421,9 +435,9 @@ public class SecurityService {
         Map<String, Object> userLoginLog = userLoginLogList.get(0);
         Object userIdObj = userLoginLog.get("userid");
         String delete = "update userloginlog set  isexpires=1, logouttime=? where userid=?  and  usertoken=? and sessionid=?";
-        DataBase.update(Config.getSecurityConnectionStr(), delete, LocalDateTime.now(), userIdObj, userToken, sessionId);
-        RequestContextHolder.currentRequestAttributes().removeAttribute("application", SCOPE_SESSION);
-        RequestContextHolder.currentRequestAttributes().removeAttribute("userinfo", SCOPE_SESSION);
+        DATABASE.update(Config.getSecurityConnectionStr(), delete, LocalDateTime.now(), userIdObj, userToken, sessionId);
+
+        Config.cache.remove(sessionId);
         return UniReturnUtil.success("成功");
     }
 
@@ -493,7 +507,7 @@ public class SecurityService {
                            null as selectcolumnlist,
                            null as filterset
                     from pageconfiguration""";
-            permission = DataBase.query(Config.getSecurityConnectionStr(), query);
+            permission = DATABASE.query(Config.getSecurityConnectionStr(), query);
         } else {
             String query = """
                     select userpermissionsid,
@@ -554,7 +568,7 @@ public class SecurityService {
                     where t3.pageconfigurationid = t1.pageconfigurationid
                       and t1.userid = ?""";
 
-            permission = DataBase.query(Config.getSecurityConnectionStr(), query, userId);
+            permission = DATABASE.query(Config.getSecurityConnectionStr(), query, userId);
         }
         return UniReturnUtil.success(permission);
     }
@@ -571,7 +585,7 @@ public class SecurityService {
         } else {
             String userId = RequestUtil.getUserId();
             String update = "update userinfo set userpassword=? where userid=?";
-            DataBase.update(Config.getSecurityConnectionStr(), update, passwordOpt.get(), userId);
+            DATABASE.update(Config.getSecurityConnectionStr(), update, passwordOpt.get(), userId);
             return UniReturnUtil.success("成功");
         }
     }
@@ -585,7 +599,7 @@ public class SecurityService {
                 update  userloginlog set
                        lastheartbeat = ?
                 where isexpires=0 and usertoken=? and sessionid=?""";
-        int updated = DataBase.update(Config.getSecurityConnectionStr(), updateSql, LocalDateTime.now(), userToken, sessionId);
+        int updated = DATABASE.update(Config.getSecurityConnectionStr(), updateSql, LocalDateTime.now(), userToken, sessionId);
         if (updated > 0) {
             return UniReturnUtil.success("成功");
         } else {
@@ -597,11 +611,11 @@ public class SecurityService {
 //      使用数据库
 //        先清理数据库中的重复请求 和过期数据
         String deleteSql = "delete from tempsecuritycode where expiretime < ? or appid = ? and requestip = ? and sessionid =? ";
-        DataBase.update(Config.getSecurityConnectionStr(), deleteSql, LocalDateTime.now(), appid, requestIp, sessionId);
+        DATABASE.update(Config.getSecurityConnectionStr(), deleteSql, LocalDateTime.now(), appid, requestIp, sessionId);
 //        新增数据
         LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(securitycodeeffective);
         String insertSql = "insert into tempsecuritycode(appid,requestip,sessionid,securitycode,expiretime) values (?,?,?,?,?)";
-        DataBase.update(Config.getSecurityConnectionStr(), insertSql, appid, requestIp, sessionId, code, localDateTime);
+        DATABASE.update(Config.getSecurityConnectionStr(), insertSql, appid, requestIp, sessionId, code, localDateTime);
 
     }
 
@@ -613,7 +627,7 @@ public class SecurityService {
                   and sessionid = ?
                   and appid = ?
                   and requestip = ?""";
-        return DataBase.update(Config.getSecurityConnectionStr(), deleteSql, code, sessionId, appid, requestIp) > 0;
+        return DATABASE.update(Config.getSecurityConnectionStr(), deleteSql, code, sessionId, appid, requestIp) > 0;
     }
 
 }

+ 3 - 2
src/main/java/com/scbfkj/uni/system/Config.java

@@ -1,19 +1,20 @@
 package com.scbfkj.uni.system;
 
 import java.util.ArrayList;
+import java.util.Hashtable;
 import java.util.List;
 import java.util.Map;
 
 
 public class Config {
+    public static final List<String> sessions = new ArrayList<>();
+    public static final Map<String, Map<String, Object>> cache = new Hashtable<>();
     public static List<Map<String, Object>> targets = new ArrayList<>();
     private static String centerConnectionStr;
     private static String securityConnectionStr;
-
     //    是否启动安全验证
     private static boolean securityEnable;
     private static boolean debug;
-
     private static String containerCode;
     //    本地日志缓存分片 10分钟
     private static int splitCount = 6000;

+ 3 - 2
src/main/java/com/scbfkj/uni/system/ScheduleUtil.java

@@ -19,6 +19,7 @@ public class ScheduleUtil {
 
     private static final ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
     private static final Map<String, ScheduledFuture<?>> scheduledFutureMap = new HashMap<>();
+    private static final DataBase DATA_BASE = new DataBase();
     public static Map<String, ScheduleTask> scheduleTaskMaps = new HashMap<>();
 
     static {
@@ -35,7 +36,7 @@ public class ScheduleUtil {
     public static boolean startService(String serviceId) throws Exception {
 
         //采集数据源及参数配置
-        List<Map<String, Object>> serviceInfos = DataBase.query(Config.getCenterConnectionStr(), "SELECT * FROM  serviceinfo  WHERE  serviceid = ?", serviceId);
+        List<Map<String, Object>> serviceInfos = DATA_BASE.query(Config.getCenterConnectionStr(), "SELECT * FROM  serviceinfo  WHERE  serviceid = ?", serviceId);
 
         if (Objects.isNull(serviceInfos) || serviceInfos.isEmpty()) {
             throw new RuntimeException("采集服务不存在");
@@ -100,7 +101,7 @@ public class ScheduleUtil {
         if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
             scheduledFuture.cancel(false);
             try {
-                DataBase.update(Config.getCenterConnectionStr(), "update serviceinfo set runState = 0 where  serviceid =?", serviceId);
+                DATA_BASE.update(Config.getCenterConnectionStr(), "update serviceinfo set runState = 0 where  serviceid =?", serviceId);
             } catch (Exception e) {
                 return UniReturnUtil.fail(e);
             }

+ 19 - 20
src/main/java/com/scbfkj/uni/system/SystemInit.java

@@ -6,7 +6,6 @@ import com.scbfkj.uni.process.DataBase;
 import com.scbfkj.uni.service.ControlService;
 import com.scbfkj.uni.service.LoggerService;
 import jakarta.annotation.PostConstruct;
-import org.flywaydb.core.Flyway;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.core.io.Resource;
 import org.springframework.core.io.support.ResourcePatternResolver;
@@ -22,9 +21,8 @@ import java.util.Scanner;
 @Component
 public class SystemInit {
 
+    private static final DataBase DATA_BASE = new DataBase();
     private final ResourcePatternResolver resourcePatternResolver;
-
-
     @Value("${db.center.config}")
     private String centerConfig;
 
@@ -64,7 +62,7 @@ public class SystemInit {
 
     private static void containerHeartbeat() {
         try {
-            DataBase.update(Config.getCenterConnectionStr(), "update container set runstate =1 ,lasttime=? where containercode=?", LocalDateTime.now(), Config.getContainerCode());
+            DATA_BASE.update(Config.getCenterConnectionStr(), "update container set runstate =1 ,lasttime=? where containercode=?", LocalDateTime.now(), Config.getContainerCode());
         } catch (Exception e) {
             HashMap<String, Object> data = new HashMap<>();
             data.put("logtime", LocalDateTime.now());
@@ -82,7 +80,8 @@ public class SystemInit {
         Config.setSecurityConnectionStr(DataEncryptionUtil.decryptRSAByPrivateKey(securityConfig));
 //        初始化数据结构
         if (enableFlyway) {
-            migrateDB();
+//            migrateDB();
+
         }
         if (enableResetConfig) {
             cleanRemoteConfig(Config.getCenterConnectionStr(), "classpath:sql/systemset/*");
@@ -91,7 +90,7 @@ public class SystemInit {
         }
 
 //        日志配置初始化
-        Config.targets.addAll(DataBase.query(Config.getCenterConnectionStr(), """
+        Config.targets.addAll(DATA_BASE.query(Config.getCenterConnectionStr(), """
                 select
                     systemid, keyname, datasourceid, expression, systemdescribe
                 from systeminfo"""));
@@ -106,7 +105,7 @@ public class SystemInit {
 //        心跳检查
         ScheduleUtil.startFrequencyTask(() -> {
             try {
-                DataBase.update(Config.getSecurityConnectionStr(), """
+                DATA_BASE.update(Config.getSecurityConnectionStr(), """
                                             update userloginlog
                         set isexpires  = 1
                         where lastheartbeat< ?""", LocalDateTime.now().plusSeconds(-60));
@@ -183,22 +182,22 @@ public class SystemInit {
                     if (Config.isDebug()) {
                         System.out.printf("执行语句:%s%n", sql);
                     }
-                    DataBase.update(connection, sql);
+                    DATA_BASE.update(connection, sql);
                 }
             }
         }
 
     }
-
-    /**
-     * 迁移数据,数据库管理
-     *
-     * @throws Exception
-     */
-    private void migrateDB() throws Exception {
-        Flyway systemSetFlyway = Flyway.configure().dataSource(DataBase.getDataSourcePool(Config.getCenterConnectionStr()).getUnwrappedDataSource()).locations("db/systemset").baselineOnMigrate(true).load();
-        systemSetFlyway.migrate();
-        Flyway uniAuthFlyway = Flyway.configure().dataSource(DataBase.getDataSourcePool(Config.getSecurityConnectionStr()).getUnwrappedDataSource()).locations("db/uniauth").baselineOnMigrate(true).load();
-        uniAuthFlyway.migrate();
-    }
+//
+//    /**
+//     * 迁移数据,数据库管理
+//     *
+//     * @throws Exception
+//     */
+//    private void migrateDB() throws Exception {
+//        Flyway systemSetFlyway = Flyway.configure().dataSource(DataBase.getDataSourcePool(Config.getCenterConnectionStr()).getUnwrappedDataSource()).locations("db/systemset").baselineOnMigrate(true).load();
+//        systemSetFlyway.migrate();
+//        Flyway uniAuthFlyway = Flyway.configure().dataSource(DataBase.getDataSourcePool(Config.getSecurityConnectionStr()).getUnwrappedDataSource()).locations("db/uniauth").baselineOnMigrate(true).load();
+//        uniAuthFlyway.migrate();
+//    }
 }

+ 13 - 0
src/test/java/com/scbfkj/uni/UniApplicationTests.java

@@ -1,7 +1,9 @@
 package com.scbfkj.uni;
 
+import com.scbfkj.uni.library.DataEncryptionUtil;
 import org.junit.jupiter.api.Test;
 
+import java.security.NoSuchAlgorithmException;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -35,4 +37,15 @@ class UniApplicationTests {
         System.out.println(stringBuilder);
     }
 
+
+    @Test
+    void test2() throws NoSuchAlgorithmException {
+        long currentTimeMillis = System.currentTimeMillis();
+        long l = currentTimeMillis << 5;
+
+        String string = DataEncryptionUtil.signatureMD5(String.valueOf(l));
+        System.out.println(string);
+
+    }
+
 }

+ 2 - 2
src/test/java/com/scbfkj/uni/api/GenericApiTest.java

@@ -11,9 +11,9 @@ class GenericApiTest extends ControllerBaseTest {
 
     @Test
     void matchService() throws Exception {
-        mockMvc.perform(MockMvcRequestBuilders.post("/openApi/hello").contentType(MediaType.APPLICATION_JSON_VALUE).content("{}"))
-                .andExpect(MockMvcResultMatchers.status().is4xxClientError())
+        mockMvc.perform(MockMvcRequestBuilders.post("/openApi/hello").contentType(MediaType.APPLICATION_JSON_VALUE).content("{}")).andExpect(MockMvcResultMatchers.status().is4xxClientError())
 
                 .andDo(MockMvcResultHandlers.print());
     }
+
 }