首页 > 其他分享 >获取druid监控数据

获取druid监控数据

时间:2022-12-02 19:34:13浏览次数:40  
标签:username org druid 获取 sysMonitors 监控 import date new


要监控spring数据 配置文件需要开启对应包扫描

spring.datasource.druid.aop-patterns= org.jeecg.modules.monitor.service.*



package org.jeecg.monitor.xxljob;

import com.alibaba.druid.stat.DruidStatManagerFacade;
import com.alibaba.druid.support.http.stat.WebAppStatManager;
import com.alibaba.druid.support.spring.stat.SpringStatManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.management.OperatingSystemMXBean;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.mqtoken.UserTokenContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.monitor.entity.SysMonitor;
import org.jeecg.modules.monitor.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 7788
 * 系统服务状态监控定时任务
 */
@Component
@Slf4j
public class SystemMonitorHandler {

    @Autowired
    private RedisUtil redisTemplate;
    @Autowired
    private SysMonitorService sysMonitorService;

    /**
     * Druid druidStatManager# 该类可以获取所有数据源的监控数据。
     */
    private final DruidStatManagerFacade druidStatManager = DruidStatManagerFacade.getInstance();
    /**
     * webAppStatManager 该类可以获取所有WEB应用的监控数据。
     */
    private final WebAppStatManager webAppStatManager = WebAppStatManager.getInstance();
    /**
     * springStatManager 该类可以获取所有spring应用的监控数据。
     */
    private final SpringStatManager springStatManager = SpringStatManager.getInstance();

    @XxlJob(value = "systemIndexMonitor")
    public ReturnT<String> systemIndexMonitor(String params) throws IOException {
        //1.设置线程会话Token
        String token = getTemporaryToken();
        UserTokenContext.setToken(token);
        String username = JwtUtil.getUsername(token);
        //2.将数据信息封装到SysMonitor对象并插入数据库
        List<SysMonitor> sysMonitors = new ArrayList<>();
        Date date = new Date();

        //3.获取系统服务器
        //内存使用率
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        long totalPhysicalMemorySize = osmxb.getTotalPhysicalMemorySize();
        long usedMemory = osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize();
        String memoryUsedRate = new DecimalFormat("#.##").format((double) usedMemory / (double) totalPhysicalMemorySize);
        //cpu使用率
        String systemCpuLoad = new DecimalFormat("#.##").format(osmxb.getSystemCpuLoad());
        log.debug("memoryUsedRate:" + memoryUsedRate);
        log.debug("cpuUsageSize:" + systemCpuLoad);

        sysMonitors.add(new SysMonitor(username, "os", SysMonitorService.CPU_USAGE, systemCpuLoad, date));
        sysMonitors.add(new SysMonitor(username, "os", SysMonitorService.MEMORY_USED, memoryUsedRate, date));
        sysMonitors.add(new SysMonitor(username, "os", SysMonitorService.MEMORY_TOTAL, transformation(totalPhysicalMemorySize), date));

        //4.系统服务器磁盘信息
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            DecimalFormat df = new DecimalFormat("0.00");
            File[] roots = File.listRoots();
            for (File file : roots) {
                long totalSpace = file.getTotalSpace();
                long freeSpace = file.getFreeSpace();
                long usedSpace = totalSpace - freeSpace;
                //转化占用磁盘大小
                float totalSpaceG = Float.parseFloat(df.format((float) totalSpace / 1024 / 1024 / 1024));
                float freeSpaceG = Float.parseFloat(df.format((float) freeSpace / 1024 / 1024 / 1024));
                float usedSpaceG = Float.parseFloat(df.format((float) usedSpace / 1024 / 1024 / 1024));
                log.debug(file + " 容量 : " + totalSpaceG + "G, 可用 : " + freeSpaceG + "G, 已用 : " + usedSpaceG + "G");
                sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(file.getAbsolutePath()), "windowsTotalSpaceG", Float.toString(totalSpaceG), date));
                sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(file.getAbsolutePath()), "windowsFreeSpaceG", Float.toString(freeSpaceG), date));
                sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(file.getAbsolutePath()), "windowsUsedSpaceG", Float.toString(usedSpaceG), date));
            }
        } else {
            try {
                Runtime rt = Runtime.getRuntime();
                Process p = rt.exec("df -hl");
                try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
                    String str;
                    int line = 0;
                    while ((str = in.readLine()) != null) {
                        line++;
                        if (line == 1) {
                            continue;
                        }
                        str = str.replaceAll("\\s+", " ");
                        String[] strArray = str.split(" ");
                        log.debug("文件系统 " + strArray[0] + ",容量 " + strArray[1] + ",已用 " + strArray[2] + ",可用 " + strArray[3] + ",占比 " + strArray[4] + ",挂载目录 " + strArray[5]);
                        sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(strArray[5]), "linuxTotalSpaceG", strArray[1], date));
                        sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(strArray[5]), "linuxfreeSpaceG", strArray[2], date));
                        sysMonitors.add(new SysMonitor(username, SysMonitorService.DISK_PREFIX.concat(strArray[5]), "linuxUsedSpaceG", strArray[3], date));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //5.获取各个子系统应用指标
        //运行监控服务指标
        List<Map<String, Object>> webAppStatDataMonitor = webAppStatManager.getWebAppStatData();
        List<Map<String, Object>> uriStatDataMonitor = webAppStatManager.getURIStatData();
        List<Map<String, Object>> dataSourceStatDataListMonitor = druidStatManager.getDataSourceStatDataList();
        List<Map<String, Object>> methodStatDataMonitor = springStatManager.getMethodStatData();
        Set<Object> springStatSet = springStatManager.getSpringStatSet();
        //处理数据
        getData("jeecg-monitor", methodStatDataMonitor, sysMonitors, webAppStatDataMonitor, uriStatDataMonitor, dataSourceStatDataListMonitor, username, date);
        //处理完数据 清空所有
        druidStatManager.resetAll();
        //其他系统服务指标

        sysMonitorService.saveBatch(sysMonitors);

        //6.使用完删除Token,避免性能差
        UserTokenContext.remove();
        return ReturnT.SUCCESS;
    }

    /**
     * 获取该模块的Druid指标值
     *
     * @param module             模块
     * @param sysMonitors        集合
     * @param webAppStatData
     * @param uriStatData
     * @param dataSourceStatData
     * @param username           用户名
     * @param date               当前时间
     */
    private void getData(String module, List<Map<String, Object>> methodStatData, List<SysMonitor> sysMonitors, List<Map<String, Object>> webAppStatData, List<Map<String, Object>> uriStatData, List<Map<String, Object>> dataSourceStatData, String username, Date date) {
        //请求总数
        long requestCount = 0;
        //jdbc连接数
        long activeCount = 0;
        //Session数量
        long httpSessionCount = 0;
        //SQL 执行数
        long logicConnectCount = 0;
        //方法执行数
        long executeCount = 0;
        //  =====================================================  spring监控 数据处理  =============================
        if (!webAppStatData.isEmpty()) {
            executeCount = methodStatData.stream().mapToLong(map -> (long) map.get("ExecuteCount")).sum();
        }
        //  =====================================================  WEB应用监控 数据处理  =============================
        if (!webAppStatData.isEmpty()) {
            Map<String, Object> webAppStatDatum = webAppStatData.get(0);
            requestCount = Long.parseLong(webAppStatDatum.get("RequestCount").toString());
            httpSessionCount = Long.parseLong(webAppStatDatum.get("SessionCount").toString());
        }
        //  =====================================================  数据源监控 数据处理  =============================
        if (!dataSourceStatData.isEmpty()) {
            //获取master数据源取值
            for (Map<String, Object> dataSourceStatDatum : dataSourceStatData) {
                if ("master".equals(dataSourceStatDatum.get("Name"))) {
                    //当前连接池中活跃连接数(当前JDBC 连接数)
                    activeCount = dataSourceStatDatum.get("ActiveCount") == null ? 0L : Long.parseLong(dataSourceStatDatum.get("ActiveCount").toString());
                    logicConnectCount = dataSourceStatDatum.get("LogicConnectCount") == null ? 0L : Long.parseLong(dataSourceStatDatum.get("LogicConnectCount").toString());
                    break;
                }
            }
        }
        sysMonitors.add(new SysMonitor(username, module, SysMonitorService.HTTP_SESSION, String.valueOf(httpSessionCount), date));
        sysMonitors.add(new SysMonitor(username, module, SysMonitorService.JDBC_ACTIVE, String.valueOf(activeCount), date));
        sysMonitors.add(new SysMonitor(username, module, SysMonitorService.JDBC_USED, String.valueOf(logicConnectCount), date));
        sysMonitors.add(new SysMonitor(username, module, SysMonitorService.REQUEST_COUNT, String.valueOf(requestCount), date));
        sysMonitors.add(new SysMonitor(username, module, SysMonitorService.EXECUTE_COUNT, String.valueOf(executeCount), date));
        log.debug("requestCount:" + requestCount);
        log.debug("activeCount:" + activeCount);
        log.debug("httpSessionCount:" + httpSessionCount);
    }


    /**
     * 获取临时令牌
     * <p>
     * 模拟登陆接口,获取模拟 Token
     *
     * @return
     */
    public static String getTemporaryToken() {
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
        //模拟登录生成临时Token
        //参数说明:第一个参数是用户名、第二个参数是密码的加密串
        String token = JwtUtil.sign("1", UUID.randomUUID().toString().replace("-", ""));
        // 设置Token缓存有效时间为 5 分钟
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, 5 * 60 * 1000);
        return token;
    }

    /**
     * 将字节容量转化为GB
     */
    public static String transformation(long size) {
        return (float) size / 1024 / 1024 / 1024 + "GB" + "   ";
    }

}


标签:username,org,druid,获取,sysMonitors,监控,import,date,new
From: https://www.cnblogs.com/qwer78/p/16945439.html

相关文章