Преглед на файлове

修改指标最新值使用redis存储

wukai преди 1 седмица
родител
ревизия
4b5db42e5b

+ 1 - 0
jjt-admin/src/main/java/com/jjt/web/controller/monitor/CacheController.java

@@ -33,6 +33,7 @@ public class CacheController {
         caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
         caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
         caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
+        caches.add(new SysCache(CacheConstants.METRICS_D_VALUE, "指标最新值"));
     }
 
     //@PreAuthorize("@ss.hasPermi('monitor:cache:list')")

+ 2 - 2
jjt-admin/src/main/java/com/jjt/web/controller/system/SysDictDataController.java

@@ -54,8 +54,8 @@ public class SysDictDataController extends BaseController {
      * 查询字典数据详细
      */
     //@PreAuthorize("@ss.hasPermi('system:dict:query')")
-    @GetMapping(value = "/{dictCode}")
-    public AjaxResult getInfo(@PathVariable Long dictCode) {
+    @GetMapping(value = "/detail")
+    public AjaxResult getInfo(Long dictCode) {
         return success(dictDataService.selectDictDataById(dictCode));
     }
 

+ 2 - 2
jjt-admin/src/main/java/com/jjt/web/controller/system/SysDictTypeController.java

@@ -48,8 +48,8 @@ public class SysDictTypeController extends BaseController {
      * 查询字典类型详细
      */
     //@PreAuthorize("@ss.hasPermi('system:dict:query')")
-    @GetMapping(value = "/{dictId}")
-    public AjaxResult getInfo(@PathVariable Long dictId) {
+    @GetMapping(value = "/detail")
+    public AjaxResult getInfo(Long dictId) {
         return success(dictTypeService.selectDictTypeById(dictId));
     }
 

+ 18 - 4
jjt-biz/src/main/java/com/jjt/biz/controller/AlarmRecordController.java

@@ -8,9 +8,11 @@ import com.jjt.biz.vo.BizAccessVO;
 import com.jjt.biz.vo.BizSortVO;
 import com.jjt.biz.vo.BizTypeVO;
 import com.jjt.biz.vo.LevelSortVO;
+import com.jjt.common.constant.CacheConstants;
 import com.jjt.common.core.controller.BaseController;
 import com.jjt.common.core.domain.AjaxResult;
 import com.jjt.common.core.page.TableDataInfo;
+import com.jjt.common.core.redis.RedisCache;
 import com.jjt.common.utils.StringUtils;
 import com.jjt.system.service.ISysDictDataService;
 import io.swagger.annotations.Api;
@@ -48,6 +50,8 @@ public class AlarmRecordController extends BaseController {
     private ISysDictDataService sysDictDataService;
     @Resource
     private IBizModelService bizModelService;
+    @Resource
+    private RedisCache redisCache;
 
     /**
      * 查询告警记录列表
@@ -185,10 +189,20 @@ public class AlarmRecordController extends BaseController {
             num = jdbcTemplate.queryForObject(sql1, Long.class, model.getModelId());
             vo.setN2(num);
 
-            sql1 = "SELECT IFNULL(SUM(d_value),0) FROM biz_obj_metrics WHERE metrics_code='D_10163' AND obj_id IN(SELECT obj_id FROM biz_model_detail where model_id=?)";
-            BigDecimal qdNum = jdbcTemplate.queryForObject(sql1, BigDecimal.class, model.getModelId());
-            if (qdNum == null) {
-                qdNum = BigDecimal.ZERO;
+            // 根据modelId和metricsCode获取objMetricsId
+            String sqlObjMetricsId = "SELECT obj_metrics_id FROM biz_obj_metrics WHERE metrics_code='D_10163' AND obj_id IN(SELECT obj_id FROM biz_model_detail where model_id=?)";
+            List<Long> objMetricsIds = jdbcTemplate.queryForList(sqlObjMetricsId, Long.class, model.getModelId());
+
+            // 从Redis中获取d_value
+            BigDecimal qdNum = BigDecimal.ZERO;
+            if (!objMetricsIds.isEmpty()) {
+                for (int i = 0; i < objMetricsIds.size(); i++) {
+                    String redisKey = CacheConstants.METRICS_D_VALUE + objMetricsIds.get(i);
+                    String dValue = redisCache.getCacheObject(redisKey);
+                    if (StringUtils.isNotEmpty(dValue)) {
+                        qdNum = qdNum.add(new BigDecimal(dValue));
+                    }
+                }
             }
             vo.setN3(qdNum.longValue());
             List<Map<String, Object>> vList = resultMap.get(model.getModelId().intValue());

+ 50 - 7
jjt-biz/src/main/java/com/jjt/biz/service/impl/BizObjMetricsServiceImpl.java

@@ -9,6 +9,8 @@ import com.jjt.biz.mapper.BizObjMetricsDataMapper;
 import com.jjt.biz.mapper.BizObjMetricsMapper;
 import com.jjt.biz.service.*;
 import com.jjt.biz.vo.AgentVO;
+import com.jjt.common.constant.CacheConstants;
+import com.jjt.common.core.redis.RedisCache;
 import com.jjt.common.exception.ServiceException;
 import com.jjt.common.utils.DateUtils;
 import com.jjt.common.utils.StringUtils;
@@ -71,6 +73,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
     private IBizObjMcService mcService;
     @Resource
     private JdbcTemplate jdbcTemplate;
+    @Resource
+    private RedisCache redisCache;
 
     /**
      * 查询业务对象指标
@@ -91,7 +95,17 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      */
     @Override
     public List<BizObjMetrics> selectBizObjMetricsList(BizObjMetrics bizObjMetrics) {
-        return bizObjMetricsMapper.selectBizObjMetricsList(bizObjMetrics);
+        List<BizObjMetrics> list = bizObjMetricsMapper.selectBizObjMetricsList(bizObjMetrics);
+        list.forEach(om -> {
+            String redisKey = CacheConstants.METRICS_D_VALUE + om.getObjMetricsId();
+            String dValue = redisCache.getCacheObject(redisKey);
+            if (StringUtils.isNotEmpty(dValue)) {
+                om.setDValue(new BigDecimal(dValue));
+            } else {
+                om.setDValue(null);
+            }
+        });
+        return list;
     }
 
     /**
@@ -454,7 +468,32 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                 }
             }
         });
-        batchUpdate(metricsToUpdate, dataList, addRList, updateRList, addEList, updateEList);
+        batchUpdate(null, dataList, addRList, updateRList, addEList, updateEList);
+//        Map<Long, BigDecimal> updateMap = new HashMap<>();
+        metricsToUpdate.forEach(mo -> {
+            String redisKey = CacheConstants.METRICS_D_VALUE + mo.getObjMetricsId();
+            redisCache.setCacheObject(redisKey, mo.getDValue().toString());
+//            updateMap.put(up.getObjMetricsId(), up.getDValue());
+        });
+//        if (updateMap.size() > 0) {
+//            // 使用Redis存储最新指标数据,避免数据库死锁问题
+//            // 批量更新Redis中的指标值
+//            updateMap.forEach((metricsId, value) -> {
+////                Map<String, String> metricData = new HashMap<>();
+////                metricData.put("dValue", value.toString());
+////                metricData.put("updateTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, updateTime));
+//                // 存储到Redis,设置过期时间(例如:1小时)
+//                // 注意:这里需要注入RedisTemplate或相关Redis操作类
+////                redisTemplate.opsForHash().putAll(redisKey, metricData);
+//                // redisTemplate.expire(redisKey, 3600, TimeUnit.SECONDS);
+//            });
+
+        // 同时更新数据库(可选,根据业务需求决定是否保留)
+//            jdbcTemplate.batchUpdate("update biz_obj_metrics set d_value = ?, UPDATE_TIME = ? where obj_metrics_id = ?",
+//                    updateMap.entrySet().stream()
+//                            .map(entry -> new Object[]{entry.getValue(), updateTime, entry.getKey()})
+//                            .collect(Collectors.toList()));
+//    }
 
     }
 
@@ -539,7 +578,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                 updateEList.add(eMap.get("update"));
             }
         });
-        batchUpdate(metricsToUpdate, dataList, addRList, updateRList, addEList, updateEList);
+        batchUpdate(null, dataList, addRList, updateRList, addEList, updateEList);
     }
 
     /**
@@ -798,10 +837,14 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
         updateJvmMetrics(objId, agentVOList, date, recordMap, eventMap, updateMap);
         updateLinkMetrics(objId, pinpointVOList, date, recordMap, eventMap, updateMap);
         if (updateMap.size() > 0) {
-            jdbcTemplate.batchUpdate("update biz_obj_metrics set d_value = ?, UPDATE_TIME = ? where obj_metrics_id = ?",
-                    updateMap.entrySet().stream()
-                            .map(entry -> new Object[]{entry.getValue(), new Date(), entry.getKey()})
-                             .collect(Collectors.toList()));
+            updateMap.forEach((key, value) -> {
+                String redisKey = CacheConstants.METRICS_D_VALUE + key;
+                redisCache.setCacheObject(redisKey, value.toString());
+            });
+//            jdbcTemplate.batchUpdate("update biz_obj_metrics set d_value = ?, UPDATE_TIME = ? where obj_metrics_id = ?",
+//                    updateMap.entrySet().stream()
+//                            .map(entry -> new Object[]{entry.getValue(), new Date(), entry.getKey()})
+//                            .collect(Collectors.toList()));
         }
     }
 

+ 1 - 1
jjt-biz/src/main/java/com/jjt/biz/service/impl/PrometheusServiceImpl.java

@@ -76,7 +76,7 @@ public class PrometheusServiceImpl implements IPrometheusService {
                 DecimalFormat df = new DecimalFormat("#0.00");
                 return Float.parseFloat(df.format(value.getFloat(1)));
             } catch (Exception e) {
-                log.error("调用prometheus接口失败, url=" + uri + ",param=" + param, e);
+                log.error("调用prometheus接口失败, url=" + uri + ",param=" + param);
                 return null;
             }
         } else {

+ 13 - 0
jjt-biz/src/main/java/com/jjt/hl/service/impl/HlMetricsServiceImpl.java

@@ -1,6 +1,9 @@
 package com.jjt.hl.service.impl;
 
+import com.jjt.common.constant.CacheConstants;
+import com.jjt.common.core.redis.RedisCache;
 import com.jjt.common.utils.DateUtils;
+import com.jjt.common.utils.StringUtils;
 import com.jjt.hl.domain.HlMetrics;
 import com.jjt.hl.mapper.HlMetricsMapper;
 import com.jjt.hl.service.IHlMetricsService;
@@ -8,6 +11,7 @@ import com.jjt.hl.vo.HlMetricsVO;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
+import java.math.BigDecimal;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -23,6 +27,8 @@ import java.util.stream.Collectors;
 public class HlMetricsServiceImpl implements IHlMetricsService {
     @Resource
     private HlMetricsMapper hlMetricsMapper;
+    @Resource
+    private RedisCache redisCache;
 
     /**
      * 查询业务模型健康度指标
@@ -134,6 +140,13 @@ public class HlMetricsServiceImpl implements IHlMetricsService {
     @Override
     public Map<Long, List<HlMetricsVO>> hlMetricsList(Long hlClassId) {
         List<HlMetricsVO> list = hlMetricsMapper.hlMetricsList(hlClassId);
+        list.forEach(hlMetricsVO -> {
+            String redisKey = CacheConstants.METRICS_D_VALUE + hlMetricsVO.getObjMetricsId();
+            String dValue = redisCache.getCacheObject(redisKey);
+            if (StringUtils.isNotEmpty(dValue)) {
+                hlMetricsVO.setDValue(new BigDecimal(dValue));
+            }
+        });
         return list.stream().collect(Collectors.groupingBy(HlMetricsVO::getMetricsId));
     }
 

+ 2 - 4
jjt-biz/src/main/java/com/jjt/risk/controller/RiskOtherController.java

@@ -22,7 +22,6 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -93,6 +92,8 @@ public class RiskOtherController extends BaseController {
                     dataMap.put("objName", md.getBizObj().getObjName() + "/" + om.getMetricsName());
                     if (om.getDValue() != null) {
                         dataMap.put("value", om.getDValue().floatValue());
+                    } else {
+                        dataMap.put("value", 0f);
                     }
                     if ("2".equals(config.getRankingBased())) {
                         String sql = "SELECT COUNT(*) num,sum(TIMESTAMPDIFF(MINUTE, alarm_time, ifnull(end_time,SYSDATE()))) times FROM alarm_record WHERE alarm_time BETWEEN ? AND ? and obj_metrics_id=?";
@@ -100,8 +101,6 @@ public class RiskOtherController extends BaseController {
                         Long num = (Long) dMap.get("num");
                         dataMap.put("alarms", num.intValue());
                         dataMap.put("value", dMap.get("times"));
-                    } else {
-                        dataMap.put("value", om.getDValue().floatValue());
                     }
                     dataList.add(dataMap);
                 }
@@ -115,7 +114,6 @@ public class RiskOtherController extends BaseController {
                         (o1, o2) -> -Integer.compare((int) o1.get("alarms"), (int) o2.get("alarms"))
                 ).collect(Collectors.toList());
             } else {
-
                 dataList = dataList.stream().sorted(
                         (o1, o2) -> -Float.compare((float) o1.get("value"), (float) o2.get("value"))
                 ).collect(Collectors.toList());

+ 3 - 6
jjt-biz/src/main/resources/mapper/alarm/AlarmRecordMapper.xml

@@ -53,8 +53,7 @@
                      c.DATA_EXP,
                      c.ALARM_LOW,
                      c.ALARM_MID,
-                     c.ALARM_HIGH,
-                     c.D_VALUE
+                     c.ALARM_HIGH
               FROM alarm_record a,
                    biz_obj b,
                    biz_obj_metrics c
@@ -129,8 +128,7 @@
                      c.DATA_EXP,
                      c.ALARM_LOW,
                      c.ALARM_MID,
-                     c.ALARM_HIGH,
-                     c.D_VALUE
+                     c.ALARM_HIGH
               FROM alarm_record a,
                    biz_obj b,
                    biz_obj_metrics c
@@ -197,8 +195,7 @@
         c.DATA_EXP,
         c.ALARM_LOW,
         c.ALARM_MID,
-        c.ALARM_HIGH,
-        c.D_VALUE
+        c.ALARM_HIGH
         FROM alarm_record a,
         biz_obj b,
         biz_obj_metrics c

+ 7 - 0
jjt-common/src/main/java/com/jjt/common/constant/CacheConstants.java

@@ -46,4 +46,11 @@ public class CacheConstants {
      */
 
     public static final String PP_APPS_MAP = "jy2024_pp_apps_map:";
+
+    /**
+     * 存储指标最新值
+     */
+    public static final String METRICS_D_VALUE = "biz_obj_metrics:value:";
+
+
 }