Explorar o código

将日志 与 机器人状态详情进行缓存,

hl hai 4 meses
pai
achega
b82a9c50e9
Modificáronse 3 ficheiros con 125 adicións e 73 borrados
  1. 73 0
      src/Interval.js
  2. 1 22
      src/robot.js
  3. 51 51
      src/web.js

+ 73 - 0
src/Interval.js

@@ -2,6 +2,10 @@ const robot = require('./robot')
 const web = require('./web')
 const {logger} = require("./utils/logger");
 const {tr} = require("date-fns/locale");
+const path = require("path");
+const file = require("./utils/file");
+const {getRustConfig} = require("./config");
+const http = require("./utils/http");
 
 
 /*******
@@ -12,6 +16,8 @@ function init() {
     reportDel()
     reportSearchPositions()
     reportAmount()
+    cacheLogs()
+    cachePredictorState()
     logger.info('--定时任务 启动');
 }
 
@@ -86,6 +92,73 @@ function reportAmount() {
     }, intervalInMilliseconds);
 }
 
+// 2024年10月28日
+// 问题: http请求过多,加上请求耗时,容易造成拥堵,所以开启线程异步缓存 机器人程序日志,机器人状态详情信息,http直接返回数据
+function cacheLogs() {
+    // 设置定时器,每隔一定时间(比如每隔5秒)发送一次GET请求
+    const intervalInMilliseconds = 1000 * 2;
+    setInterval(() => {
+        // logger.info('当前2',robot.appMap);
+        robot.appMap.forEach((value, key) => {
+            var thisTime = new Date().getTime()
+            let port = value.port
+            let n = 200
+            let messlist = value.messlist
+            if (value.id !== -1 && port !== -1) {
+                logger.info(`~~~缓存日志${value.id}`)
+                try {
+                    var logPath = "./logs" + port
+                    logger.info(`访问-日志相对目录:${logPath}`)
+                    const directoryPath = path.resolve(logPath);
+                    file.checkPathSync(directoryPath)
+                    file.getLastFile(logPath, 5, async (fileNameList, _) => {
+                        let result = await file.getLatestLogEntries(logPath, fileNameList.reverse(), n);
+                        if (messlist.length === 0) {
+                            value.messlist = result
+                        } else {
+                            if (messlist[0] !== result[0]) {
+                                value.messlist = result
+                            }
+                        }
+                    });
+                } catch (e) {
+                    logger.info('异步缓存日志异常~~', e);
+                }
+            }
+        });
+    }, intervalInMilliseconds);
+}
+
+function cachePredictorState() {
+    // 设置定时器,每隔一定时间(比如每隔5秒)发送一次GET请求
+    const intervalInMilliseconds = 1500;
+    setInterval(() => {
+        // logger.info('当前2',robot.appMap);
+        var config = getRustConfig()
+        robot.appMap.forEach((value, key) => {
+            var thisTime = new Date().getTime()
+            let port = value.port
+            let predictorState = value.predictorState
+            if (value.id !== -1 && port !== -1) {
+                logger.info(`~~~缓存机器人状态详情${value.id}`)
+                var accUrl = "http://127.0.0.1:" + port
+                http.request_get(`${accUrl}/predictor_state`, {...config.headers})
+                    .then((data) => {
+                        let result =  JSON.parse(data);
+                        if (predictorState.length === 0) {
+                            value.predictorState = result
+                        } else {
+                            if (predictorState[0] !== predictorState[0]) {
+                                value.predictorState = result
+                            }
+                        }
+                    }).catch((error) => {
+                    logger.info(`异步缓存predictorState异常~~ ${error.message}`)
+                });
+            }
+        });
+    }, intervalInMilliseconds);
+}
 
 module.exports = {
     init

+ 1 - 22
src/robot.js

@@ -43,6 +43,7 @@ function getApp(key) {
         nowBalance: -1,
         posNum: -1,
         messlist: [],
+        predictorState:[],
         threadStatus: RobotStatus.STOPPED,
         errorMessage: "成功",
         threadStartTime: -1,
@@ -553,27 +554,6 @@ function delRobot(app) {
 
 //----------------------------------------------
 
-// 新策略-获取状态
- function predictorState(app) {
-    var accUrl = "http://127.0.0.1:" + app.port
-    //拿到策略余额
-    try {
-        var config = getRustConfig()
-        http.request_get(`${accUrl}/predictor_state`, {...config.headers})
-            .then((data) => {
-                var d = JSON.parse(data)
-                return {'code': 200, 'data': d, "message": "SUCCESS"}
-            }).catch((error) => {
-            // 处理可能发生的错误
-            logger.error(`#####################汇报:获取状态请求失败: ${error.message}`)
-            return {'code': -1, 'data': null, "message": `获取状态请求失败${error.message}`}
-        });
-    } catch (e) {
-        logger.error('请求失败!:', e)
-        return {'code': -1, 'data': null, "message": "获取状态请求出错"}
-    }
-
-}
 
 module.exports = {
     run,
@@ -584,7 +564,6 @@ module.exports = {
     robotAmount,
     closeAppAll,
     searchPositions,
-    predictorState,
     appMap,
     getApp,
     getAppMap,

+ 51 - 51
src/web.js

@@ -75,45 +75,48 @@ function init() {
         const param = req.query;
         const n = param.n
         const id = param.id
+        let result = [];
 
         var port = -1;
         robot.appMap.forEach((value, key) => {
             // logger.info(JSON.stringify(value))
             if (value.id + "" === id + "") {
                 port = value.port
+                result = value.messlist
             }
         })
-
-        let result = [];
-        if (port !== -1) {
-            var logPath = "./logs" + port
-            logger.info(`访问-日志相对目录:${logPath}`)
-            // 将相对路径转换为绝对路径
-            const directoryPath = path.resolve(logPath);
-            try {
-                // logger.info(`---------------------2`)
-                file.checkPathSync(directoryPath)
-                // logger.info(`---------------------3`)
-                file.getLastFile(logPath, 5, async (fileNameList, _) => {
-                    // logger.info(`---------------------5`)
-                    // logger.info('cccccccccccccc文件:', fileNameList);
-
-                    // result = await file.readLastNLines(logPath, fileNameList, n);
-                    // result =  await  file.getRecentLogs(logPath,fileNameList.reverse(),n);
-                    result =  await  file.getLatestLogEntries(logPath,fileNameList.reverse(),n);
-
-
-                    // logger.info('?????:', result);
-                    // logger.info(`---------------------6`)
-                    res.send({'code': 200, 'data': result, "message": "SUCCESS"});
-                });
-            } catch (e) {
-                logger.info('获取日志异常了~~', e);
-                res.send({'code': 200, 'data': [], "message": "SUCCESS"});
-            }
-        } else {
-            res.send({'code': 200, 'data': result, "message": "SUCCESS"});
-        }
+        res.send({'code': 200, 'data': result, "message": "SUCCESS"});
+
+
+        // if (port !== -1) {
+        //     var logPath = "./logs" + port
+        //     logger.info(`访问-日志相对目录:${logPath}`)
+        //     // 将相对路径转换为绝对路径
+        //     const directoryPath = path.resolve(logPath);
+        //     try {
+        //         // logger.info(`---------------------2`)
+        //         file.checkPathSync(directoryPath)
+        //         // logger.info(`---------------------3`)
+        //         file.getLastFile(logPath, 5, async (fileNameList, _) => {
+        //             // logger.info(`---------------------5`)
+        //             // logger.info('cccccccccccccc文件:', fileNameList);
+        //
+        //             // result = await file.readLastNLines(logPath, fileNameList, n);
+        //             // result =  await  file.getRecentLogs(logPath,fileNameList.reverse(),n);
+        //             result =  await  file.getLatestLogEntries(logPath,fileNameList.reverse(),n);
+        //
+        //
+        //             // logger.info('?????:', result);
+        //             // logger.info(`---------------------6`)
+        //             res.send({'code': 200, 'data': result, "message": "SUCCESS"});
+        //         });
+        //     } catch (e) {
+        //         logger.info('获取日志异常了~~', e);
+        //         res.send({'code': 200, 'data': [], "message": "SUCCESS"});
+        //     }
+        // } else {
+        //     res.send({'code': 200, 'data': result, "message": "SUCCESS"});
+        // }
     });
     app.post('/execute', (req, res) => {
         // 获取发送过来的信息(请求体的数据)
@@ -142,36 +145,33 @@ function init() {
     })
     // 新策略-返回机器人状态
     app.get('/predictorState', (req, res) => {
-
-        // const param = req.query;
-        // logger.info(JSON.stringify(param));
-        // let data = robot.predictorState(param)
-        // res.send(data);
-
         const param = req.query;
         const id = param.id
+        let result = []
 
         var port = -1;
         robot.appMap.forEach((value, key) => {
             // logger.info(JSON.stringify(value))
             if (value.id + "" === id + "") {
                 port = value.port
+                result = value.predictorState
             }
         })
-
-        var accUrl = "http://127.0.0.1:" + port
-        var config = getRustConfig()
-        logger.info(`#####################开始:`)
-        http.request_get(`${accUrl}/predictor_state`, {...config.headers})
-            .then((data) => {
-                // logger.info(`#####################返回数据:`,data)
-                res.send({'code': 200, 'data':  JSON.parse(data), "message": "SUCCESS"});
-            }).catch((error) => {
-            // 处理可能发生的错误
-            logger.info(`#####################汇报:获取状态请求失败: ${error.message}`)
-            res.send({'code': -1, 'data': null, "message": `获取状态请求失败${error.message}`});
-        });
-        logger.info(`#####################最后:`)
+        res.send({'code': 200, 'data': result, "message": "SUCCESS"});
+
+        // var accUrl = "http://127.0.0.1:" + port
+        // var config = getRustConfig()
+        // logger.info(`#####################开始:`)
+        // http.request_get(`${accUrl}/predictor_state`, {...config.headers})
+        //     .then((data) => {
+        //         // logger.info(`#####################返回数据:`,data)
+        //         res.send({'code': 200, 'data':  JSON.parse(data), "message": "SUCCESS"});
+        //     }).catch((error) => {
+        //     // 处理可能发生的错误
+        //     logger.info(`#####################汇报:获取状态请求失败: ${error.message}`)
+        //     res.send({'code': -1, 'data': null, "message": `获取状态请求失败${error.message}`});
+        // });
+        // logger.info(`#####################最后:`)
     })
     // 使服务器监听特定端口
     app.listen(port, () => {