首页 > 其他分享 >使用普罗米修斯API统计服务宕机时间

使用普罗米修斯API统计服务宕机时间

时间:2024-08-05 17:06:06浏览次数:13  
标签:String 宕机 普罗米修斯 System long API println startDTO out

使用/api/v1/query?query=mysql_global_status_uptime&time=

查询服务上次启动时间

使用/api/v1/query_range

String query = "mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"}";

  查询某段时间内服务的数据变化

通过60秒和1秒的step来分析出服务的实际宕机时间

具体代码如下

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>prometheus-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!--添加fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <!--tomcat容器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.18</version>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>
        <!-- HttpClient依赖 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

        <!-- Jackson依赖 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.java.MysqlServiceAnalysisTestSecond002</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>



</project>

logback.xml

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>

    <logger name="org.springframework.web.client.RestTemplate" level="info" />
</configuration>

  工具类

package com.java.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2024/8/1 14:53
 */
public class TimeTransUtil {

    /**
     * 适用于2024-05-23 19:43:27这种格式的
     * @param timestamp
     * @return
     */
    public static String convertTimestampToDate(long timestamp) {
        // 创建一个 SimpleDateFormat 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 例如设置为中国时区

        // 创建一个 Date 对象
        Date date = new Date(timestamp * 1000); // 时间戳是以秒为单位,所以乘以1000转换为毫秒

        // 格式化日期
        return sdf.format(date);
    }

//    public static void main(String[] args) {
//        String calActDownTime = calActDownTime(572);
//        System.out.println("calActDownTime = " + calActDownTime);
//    }

    public static String calActDownTime(long time){
        if (time==0){
            return "0";
        }
        if (time<60){
            return time+"秒";
        }
        long l = time / 60;
        if (l*60==time){
            return l+"分钟";
        }
        long l1 = time-l * 60;
        return l+"分钟"+l1+"秒";

    }

}

  

package com.java.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.bean.StartDTO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Description:
 * @Author: tutu-qiuxie
 * @Create: 2024/7/8 2:44
 */
public class TimeDealUtil {

    public static Long timeTransfer(String startTime){

        try {
            // 创建日期格式化对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));

            // 将截止时间字符串解析为日期对象
            Date endTime = sdf.parse(startTime);

            // 计算启动时间的时间戳(秒)
            long endTimeMillis = endTime.getTime() / 1000; // 转换为秒
            return endTimeMillis;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    public static long transferTime(String startTime,String endTime){
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析日期
        LocalDateTime start = LocalDateTime.parse(startTime, formatter);
        LocalDateTime end = LocalDateTime.parse(endTime, formatter);

        // 计算时间差
        Duration duration = Duration.between(start, end);
        long uptimeSeconds = duration.getSeconds();
        return uptimeSeconds;
    }


    public static StartDTO calRestartTime(long uptimeSeconds, String closeTime){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));

        try {
            Date parse = dateFormat.parse(closeTime);
            long l = parse.getTime() / 1000;
            long startTimeSeconds = l - uptimeSeconds;
            Date startTime = new Date(startTimeSeconds * 1000); // 转换回毫秒
            // 格式化启动时间
            String startTimeStr = dateFormat.format(startTime);
            return StartDTO.builder().startTimeSeconds(startTimeSeconds).startTimeStr(startTimeStr).build();

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String dealTime1(long timestamp){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 例如设置为中国时区

        // 创建一个 Date 对象
        Date date = new Date(timestamp * 1000); // 时间戳是以秒为单位,所以乘以1000转换为毫秒

        // 格式化日期
        return sdf.format(date);
    }

    public static String dealTime(double timestamp){
        // 将 Unix 时间戳转换为秒和纳秒
        long seconds = (long) timestamp;
        int nanos = (int) ((timestamp - seconds) * 1_000_000_000);
        // 转换为 LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanos), ZoneId.systemDefault());
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化日期时间
        String formattedDateTime = dateTime.format(formatter);
        return formattedDateTime;
    }

    public static String statNommalToDownTime001(String baseUrl, String query,String binstance, long start, long end, int step){
        // 1. 设置 RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 2. 创建 HttpHeaders 并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 如果有其他请求头,继续设置
        headers.set("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIwMzUzNTgwNTQsImlzcyI6Imh0dHA6Ly9hbGliYWJhY2xvdWQuY29tIiwiaWF0IjoxNzE5OTk4MDU0LCJqdGkiOiIzZTMzYzc5ZS1kNjE2LTQzNmEtOWNjNi04MjU2NjlkOWVkOGYifQ.R8HP2xIDHh6fYLXIFnPmekzTfre3J3Npxdq67jsMqos");
        // 设置 Accept-Charset header
        headers.set("Accept-Charset", "UTF-8");
        // 3. 创建 HttpEntity 并将 HttpHeaders 设置到其中
        HttpEntity<String> entity = new HttpEntity<>(headers);
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("query", query)
                .queryParam("start", start)
                .queryParam("end", end)
                .queryParam("step", step+"s")
                .build()
                .encode()
                .toUri();

        // 5. 使用 RestTemplate 发送请求并接收响应
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        // 6. 返回响应结果
        return response.getBody();

    }


    /**
     * 统计出正常运行到宕机之间的时间
     * @param baseUrl
     * @param query
     * @param start
     * @param end
     * @param step
     * @return
     */
    public static String statNommalToDownTime(String baseUrl, String query,String binstance, long start, long end, int step){
        // 1. 设置 RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 2. 创建 HttpHeaders 并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 如果有其他请求头,继续设置
        headers.set("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIwMzUzNTgwNTQsImlzcyI6Imh0dHA6Ly9hbGliYWJhY2xvdWQuY29tIiwiaWF0IjoxNzE5OTk4MDU0LCJqdGkiOiIzZTMzYzc5ZS1kNjE2LTQzNmEtOWNjNi04MjU2NjlkOWVkOGYifQ.R8HP2xIDHh6fYLXIFnPmekzTfre3J3Npxdq67jsMqos");
        headers.set("Accept-Charset", "UTF-8");  // 设置 Accept-Charset header
        // 3. 创建 HttpEntity 并将 HttpHeaders 设置到其中
        HttpEntity<String> entity = new HttpEntity<>(headers);
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("query", query)
                .queryParam("Binstance",binstance)
                .queryParam("start", start)
                .queryParam("end", end)
                .queryParam("step", step+"s")
                .build()
                .encode()
                .toUri();

        // 5. 使用 RestTemplate 发送请求并接收响应
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        // 6. 返回响应结果
        return response.getBody();

    }

    public static String calActDownTime(long time){
        if (time<60){
            return time+"秒";
        }
        long l = time / 60;
        return l+"分钟";

    }


    public static Map<String,Long> test0013(JSONArray valuesArray,StartDTO startDTO){
        Map<String, Long> map = new HashMap<>(16);
        System.out.println("valuesArray.size()=" + valuesArray.size());
        calMysqlServiceRestartTime13(valuesArray,map);


        //System.out.println("resultsArray = " + resultsArray);

//        for (int i = 0; i < resultsArray.size(); i++) {
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            JSONObject resultObject = resultsArray.getJSONObject(i);
//            //System.out.println("resultObject = " + resultObject);
//
//            JSONObject metricObject = resultObject.getJSONObject("metric");
//           // System.out.println("metricObject = " + metricObject);
////            String instance = metricObject.getString("instance");
////            System.out.println("instance = " + instance);
//            JSONArray valuesArray = resultObject.getJSONArray("values");
//            System.out.println("valuesArray = " + valuesArray);
//        }



//        for (int i = 0; i < resultsArray.size(); i++) {
//            JSONObject resultObject = resultsArray.getJSONObject(i);
//
//            JSONObject metricObject = resultObject.getJSONObject("metric");
//            String instance = metricObject.getString("instance");
//            System.out.println("instance = " + instance);
//            JSONArray valuesArray = resultObject.getJSONArray("values");
//           // List<Long> downtimes = new ArrayList<>();
//            calMysqlServiceRestartTime12(valuesArray,map);
//            //map.put("lastStartTime",downtimes.get(0));
//
//
//        }
        return map;

    }

    /**
     * 拿到最后一次运行时间,和重启后捕获的第一次时间
     * @param resultsArray
     */
    public static Map<String,Long> test0012(JSONArray resultsArray){
        //System.out.println("服务器总数="+resultsArray.size());
        Map<String,Long> map=new HashMap<>(16);
        for (int i = 0; i < resultsArray.size(); i++) {
            JSONObject resultObject = resultsArray.getJSONObject(i);

            JSONObject metricObject = resultObject.getJSONObject("metric");
            String instance = metricObject.getString("instance");
            JSONArray valuesArray = resultObject.getJSONArray("values");
            List<Long> downtimes = new ArrayList<>();
            calMysqlServiceRestartTime1(downtimes,valuesArray,map);
            map.put("lastStartTime",downtimes.get(0));

            // 输出结果
//            if (downtimes.isEmpty()) {
//                 System.out.println("没有检测到重启。");
//            } else {
//                System.out.println("检测到 " + downtimes.size() + " 次重启。");
//                for (int k = 0; k < downtimes.size(); k++) {
//                      System.out.println("重启前的运行时间: " + downtimes.get(k) + " 秒");
//                    map.put("restartTime",downtimes.get(k));
//                }
//            }

        }
        return map;

    }

    public static void calMysqlServiceRestartTime13(JSONArray valuesArray,Map<String,Long> map){

        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
             System.out.println("valuePair = " + valuePair);
            long currentUptime = valuePair.getLong(0);
//            System.out.println("当前时间 = " + convertTimestampToDate(currentUptime));
            long value = valuePair.getLong(1);
            System.out.println(currentUptime+","+value);
//            System.out.println("运行时间 = " + convertSecondsToTime(value));
        }

    }

    public static void calMysqlServiceRestartTime12(JSONArray valuesArray,Map<String,Long> map){

        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
            // System.out.println("valuePair = " + valuePair);
            long currentUptime = valuePair.getLong(0);
             System.out.println("当前时间 = " + convertTimestampToDate(currentUptime));
            long value = valuePair.getLong(1);
             System.out.println("运行时间 = " + convertSecondsToTime(value));
            if (j>0){
                JSONArray valuePairFirst = valuesArray.getJSONArray(j-1);
                long currentUptimeFirst = valuePairFirst.getLong(0);
                long valueFirst = valuePairFirst.getLong(1);
//                if (currentUptimeFirst==currentUptime){
//                    System.out.println("上次时间:" + convertTimestampToDate(currentUptimeFirst) + ",已运行时间=" + valueFirst);
//                    System.out.println("当前时间:" + convertTimestampToDate(currentUptime) + ",已运行时间=" + value);
//                    break;
//                }
                if (currentUptimeFirst==currentUptime){

                }else{
                    //JSONArray valuePairLast = valuesArray.getJSONArray(valuesArray.size() - 1);
                    long currentUptimeLast = valuePair.getLong(0);
                    long valueLast = valuePair.getLong(1);
                    if (j==valuesArray.size() - 1){
                        map.put("lastLiveTime", currentUptimeLast);
                        map.put("upTime", valueLast);
                    }

                }
            }
        }

    }

    /**
     * 将秒数转换为小时、分钟和秒数的方法
     * @param totalSeconds
     * @return
     */
    public static String convertSecondsToTime(long totalSeconds) {
        long hours = totalSeconds / 3600; // 计算小时数
        long remainingSecondsAfterHours = totalSeconds % 3600;

        long minutes = remainingSecondsAfterHours / 60; // 计算分钟数
        long seconds = remainingSecondsAfterHours % 60; // 计算剩余秒数

        return hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒";
    }

    public static void calMysqlServiceRestartTime1(List<Long> downtimes,JSONArray valuesArray,Map<String,Long> map){
        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
           // System.out.println("valuePair = " + valuePair);
            long currentUptime = valuePair.getLong(0);
           // System.out.println("当前时间 = " + convertTimestampToDate(currentUptime));
            long value = valuePair.getLong(1);
           // System.out.println("运行时间 = " + value);
            if (j>0){
                JSONArray valuePairFirst = valuesArray.getJSONArray(j-1);
                long currentUptimeFirst = valuePairFirst.getLong(0);
                long valueFirst = valuePairFirst.getLong(1);
                if (value-valueFirst==0){
                   // System.out.println("上次时间:"+convertTimestampToDate(currentUptimeFirst)+",已运行时间="+valueFirst);
                   // System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                    downtimes.add(currentUptimeFirst);
                    break;
                }
            }
        }

    }

    /**
     * 计算mysql服务的重启消耗时间
     */
    public static void calMysqlServiceRestartTime(List<Long> downtimes,JSONArray valuesArray,Map<String,Long> map){

        long lastUptime = valuesArray.getJSONArray(0).getLong(1);
         System.out.println("lastUptime = " + lastUptime);

        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
             System.out.println("valuePair = " + valuePair);
            long currentUptime = valuePair.getLong(0);
            long value = valuePair.getLong(1);
             System.out.println("value = " + value);
              System.out.println("当前时间:" + convertTimestampToDate(currentUptime));
             System.out.println(value - lastUptime);
            if (value - lastUptime <0) {
                //System.out.println("currentUptime="+currentUptime);
                JSONArray valuePair1 = valuesArray.getJSONArray(j-1);
                long currentUptime1 = valuePair1.getLong(0);
                long value1 = valuePair1.getLong(1);
                  System.out.println("上次时间:"+convertTimestampToDate(currentUptime1)+",已运行时间="+value1);
                 System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                map.put("firstStartTime",value);
                map.put("startTime",currentUptime1);
                map.put("endTime",currentUptime);
                long reStartTime=currentUptime-currentUptime1;

                // 检测到重启
                downtimes.add(reStartTime);
                break;
            }else {
                //System.out.println("重启了");
            }
            //lastUptime = currentUptime;

        }

    }

    /**
     * 时间戳转为日期
     * @param timestamp
     * @return
     */
    public static String convertTimestampToDate(long timestamp) {
        if(timestamp==0){
            return "无";
        }
       // System.out.println("timestamp="+timestamp);
        // 创建一个 SimpleDateFormat 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 例如设置为中国时区

        // 创建一个 Date 对象
        Date date = new Date(timestamp * 1000); // 时间戳是以秒为单位,所以乘以1000转换为毫秒

        // 格式化日期
        return sdf.format(date);
    }

}

  

package com.java.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.MysqlServiceAnalysisTestSecond002;
import com.java.bean.StartDTO;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2024/8/1 16:19
 */
public class QueryUpTimeBySecondUtil {

    /**
     * 入口
     * @param currentUptime
     * @param startDTO
     * @param lists
     */
    public static void calSecnods(long currentUptime,StartDTO startDTO, List<Map<String, Long>> lists){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析给定的时间字符串
        String givenTimeString = TimeTransUtil.convertTimestampToDate(currentUptime);
        LocalDateTime givenTime = LocalDateTime.parse(givenTimeString, formatter);
        // 打印给定时间
        System.out.println("给定时间: " + givenTimeString);
        // 计算前5分钟
        LocalDateTime fiveMinutesBefore = givenTime.minusMinutes(10);
        System.out.println("前10分钟: " + fiveMinutesBefore.format(formatter));
        // 计算后5分钟
        LocalDateTime fiveMinutesAfter = givenTime.plusMinutes(10);
        System.out.println("后10分钟: " + fiveMinutesAfter.format(formatter));
        // 输出结果
        long originTime=TimeDealUtil.timeTransfer(fiveMinutesBefore.format(formatter));
        long endTime=TimeDealUtil.timeTransfer(fiveMinutesAfter.format(formatter));
        String query1 = "mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"}";
        String statusUptime = TimeDealUtil.statNommalToDownTime001(MysqlServiceAnalysisTestSecond002.url + "/api/v1/query_range?", query1, startDTO.getInstance(), originTime, endTime, 1);
        JSONObject jsonObject2 = JSON.parseObject(statusUptime);
        JSONObject jsonObject21 = jsonObject2.getJSONObject("data");
        JSONArray resultsArray22 = jsonObject21.getJSONArray("result");
        test0014(resultsArray22,lists,endTime);
    }

    private static void test0014(JSONArray Array,List<Map<String, Long>> lists,long endTime){
        for (int i = 0; i < Array.size(); i++) {
            JSONObject resultObject = Array.getJSONObject(i);
            JSONArray valuesArray = resultObject.getJSONArray("values");
            calMysqlServiceRestartTime001(valuesArray,lists,endTime);
        }
    }

    private static void calMysqlServiceRestartTime001(JSONArray valuesArray,List<Map<String, Long>> lists,long endTime){

        long lastUptime = valuesArray.getJSONArray(0).getLong(1);
        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
            long currentUptime = valuePair.getLong(0);
            long value = valuePair.getLong(1);
            if (value<lastUptime){
                JSONArray valuePair1 = valuesArray.getJSONArray(j-1);
                long currentUptime1 = valuePair1.getLong(0);
                long value1 = valuePair1.getLong(1);
                System.out.println("上次时间:"+TimeTransUtil.convertTimestampToDate(currentUptime1)+",已运行时间="+value1);
                System.out.println("当前时间:"+TimeTransUtil.convertTimestampToDate(currentUptime)+",已运行时间="+value);
                long reStartTime=currentUptime-currentUptime1;
                System.out.println("宕机时间="+TimeTransUtil.calActDownTime(reStartTime));
                if (reStartTime!=0){
                    Map<String,Long> longMap=new HashMap<>(16);
                    longMap.put("lastLiveTime",currentUptime1);
                    longMap.put("upTime",value1);
                    longMap.put("downLiveTime",reStartTime);
                    lists.add(longMap);
                }
                break;

            }else if (j==valuesArray.size() - 1){
                long reStartTime=endTime-currentUptime;
                if (reStartTime>0){
                    System.out.println("QueryUpTimeBySecondUtil--当前时间:"+TimeTransUtil.convertTimestampToDate(currentUptime)+",已运行时间="+value);
                    System.out.println("QueryUpTimeBySecondUtil--截止时间:"+TimeTransUtil.convertTimestampToDate(endTime));
                    System.out.println("QueryUpTimeBySecondUtil--非正常计算宕机时间:"+reStartTime);
                    Map<String,Long> longMap=new HashMap<>(16);
                    longMap.put("downLiveTime",reStartTime);
                    lists.add(longMap);
                }
            }

        }

    }
}

  

package com.java.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.MysqlServiceAnalysisTestSecond002;
import com.java.bean.StartDTO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2024/8/1 14:52
 */
public class AbsentUtil {

    /**
     * 入口
     * @param startTime
     * @param lastStartTime
     * @param startDTO
     * @param lists
     */
    public static void calDownTimeBySeconds(String startTime, String lastStartTime, StartDTO startDTO, List<Map<String, Long>> lists){

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.parse(lastStartTime, formatter);
        LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime cutoffTime = startDateTime.minusMinutes(20);

        while (!endTime.isBefore(startDateTime)) {
            LocalDateTime previousHour = endTime.minusHours(1);

            if (previousHour.isBefore(startDateTime)) {
                //calSecnods(startTime,endTime.format(formatter),startDTO,lists);
                break;
            } else {
                //System.out.println(previousHour.format(formatter) + " - " + endTime.format(formatter));
                calSecnods(previousHour.format(formatter),endTime.format(formatter),startDTO,lists);
                endTime = previousHour;
            }
        }
    }

    private static void calSecnods(String startTime,String closeTime,StartDTO startDTO,List<Map<String, Long>> lists){
        // 输出结果
        long originTime=TimeDealUtil.timeTransfer(startTime);
        long endTime=TimeDealUtil.timeTransfer(closeTime);
        String query1 = "absent(mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"})";
        String statusUptime = statNommalToDownTime001(MysqlServiceAnalysisTestSecond002.url + "/api/v1/query_range?", query1, originTime, endTime, 1);
        JSONObject jsonObject = JSON.parseObject(statusUptime);
        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
        JSONArray resultsArray = jsonObject1.getJSONArray("result");
        test100(resultsArray,lists);
    }


    private static void test100(JSONArray resultArray,List<Map<String, Long>> lists){
        for (int k = 0; k < resultArray.size(); k++) {
            JSONObject resultObject = resultArray.getJSONObject(k);
            JSONObject metricObject = resultObject.getJSONObject("metric");
            System.out.println("metricObject = " + metricObject);
            JSONArray values = resultObject.getJSONArray("values");
            int size = values.size();
            JSONArray valuePair = values.getJSONArray(0);
            long firstTime = valuePair.getLong(0);
            JSONArray jsonArray = values.getJSONArray(size - 1);
            long lastTime = jsonArray.getLong(0);
            long downTime = lastTime - firstTime;
            System.out.println("宕机开始时间:"+TimeTransUtil.convertTimestampToDate(firstTime));
            System.out.println("宕机结束时间:"+TimeTransUtil.convertTimestampToDate(lastTime));
            System.out.println("宕机时间: " + TimeTransUtil.calActDownTime(downTime));
            Map<String,Long> longMap=new HashMap<>(16);
            longMap.put("downLiveTime",downTime);
            lists.add(longMap);
            //  test101(values);
        }

    }

    private static String statNommalToDownTime001(String baseUrl, String query, long start, long end, int step){
        // 1. 设置 RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 2. 创建 HttpHeaders 并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 如果有其他请求头,继续设置
        headers.set("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIwMzUzNTgwNTQsImlzcyI6Imh0dHA6Ly9hbGliYWJhY2xvdWQuY29tIiwiaWF0IjoxNzE5OTk4MDU0LCJqdGkiOiIzZTMzYzc5ZS1kNjE2LTQzNmEtOWNjNi04MjU2NjlkOWVkOGYifQ.R8HP2xIDHh6fYLXIFnPmekzTfre3J3Npxdq67jsMqos");
        // 设置 Accept-Charset header
        headers.set("Accept-Charset", "UTF-8");
        // 3. 创建 HttpEntity 并将 HttpHeaders 设置到其中
        HttpEntity<String> entity = new HttpEntity<>(headers);
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("query", query)
                .queryParam("start", start)
                .queryParam("end", end)
                .queryParam("step", step+"s")
                .build()
                .encode()
                .toUri();

        // 5. 使用 RestTemplate 发送请求并接收响应
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        // 6. 返回响应结果
        return response.getBody();

    }

}

  实体类

package com.java.bean;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Description:
 * @Author: tutu-qiuxie
 * @Create: 2024/7/7 12:18
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class StartDTO {

    /**
     * 启动时间
     */
    private String startTimeStr;

    private long startTimeSeconds;

    /**
     * 存活时间
     */
    private long uptimeSeconds;

    private String endTime;

    private String instance;

    private String business2;

    /**
     * 宕机时间
     */
    private String downTime;

    /**
     * 宕机前最后的活跃时间
     */
    private long downLiveTime;

    /**
     * 宕机前最后存活时间
     */
    private String lastLiveTime;

    /**
     * 从来就没有启动
     */
    private long neverStartTime;

    /**
     * 宕机次数
     */
    private int downNum;
}

主类

package com.java;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.bean.StartDTO;
import com.java.util.AbsentUtil;
import com.java.util.QueryUpTimeBySecondUtil;
import com.java.util.TimeDealUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: 喵星人
 * @Create: 2024/7/10 13:15
 */
public class MysqlServiceAnalysisTestSecond002{

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String url="";
    public static final long STOP_DATE = 1719936000L;

    public static void main(String[] args) {

      String startTime = "2024-07-03 00:00:00";
      String lastTime = "2024-07-31 21:20:00";

        String response = getMysqlInstanceList1(TimeDealUtil.timeTransfer(lastTime));
        JSONObject jsonObject = JSON.parseObject(response);
        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
        JSONArray resultsArray = jsonObject1.getJSONArray("result");
        List<StartDTO> instanceList=new ArrayList<>(10);
        getMysqlInstanceLastStartTime(resultsArray, startTime,instanceList);
        Long transfer = TimeDealUtil.timeTransfer(startTime);
        List<StartDTO> calList=new ArrayList<>();
        //*******************
        for (StartDTO startDTO : instanceList) {
            try {
                if (startDTO.getStartTimeStr() == null) {
                    calList.add(startDTO);
                    continue;
                }
                String instance=startDTO.getInstance();
                System.out.println("机器实例 instance = " + instance);
                Map<String, Long> stringLongMap = new HashMap<>(16);
                List<Map<String, Long>> list=new ArrayList<>(10);
                fetchDataRecursively(startDTO, sdf.parse(startDTO.getStartTimeStr()), stringLongMap,list);

                String startTimeStr=startDTO.getStartTimeStr();
                System.out.println("startTimeStr = " + startTimeStr);

                System.out.println("stringLongMap = " + stringLongMap);
                long downLiveTime = list.stream()
                        .mapToLong(map -> map.get("downLiveTime"))
                        .sum();
                if (downLiveTime==0L){
                    System.out.println("按照1秒查询");
                    List<Map<String, Long>> lists=new ArrayList<>(10);
                    calDownTimeBySeconds(startTime,startDTO.getStartTimeStr(),startDTO,lists);
                    long downLiveTime1 = lists.stream()
                            .mapToLong(map -> map.get("downLiveTime"))
                            .sum();
                    startDTO.setDownTime(calActDownTime(downLiveTime1));
                    startDTO.setDownNum(lists.size());

                }else {
                    System.out.println("按照60秒查询");
                    startDTO.setDownTime(calActDownTime(downLiveTime));
                    startDTO.setDownNum(list.size());
                }

                if ("0".equals(startDTO.getDownTime())){
                   StringBuffer stringBuffer=new StringBuffer();
                   stringBuffer.append(startTime);
                   stringBuffer.append("~");
                   stringBuffer.append(startDTO.getStartTimeStr());
                   stringBuffer.append("没有数据");
                   startDTO.setDownTime(stringBuffer.toString());
                }
                List<Map<String, Long>> absentList = new ArrayList<>(10);
                AbsentUtil.calDownTimeBySeconds(startTime, lastTime, startDTO, absentList);
                long downLiveTime1 = absentList.stream()
                        .mapToLong(map -> map.get("downLiveTime"))
                        .sum();
                System.out.println("使用absent计算的宕机时间:"+downLiveTime1);




                System.out.println("startDTO.getDownTime()=" + startDTO.getDownTime());
//                if (startDTO.getDownTime() == null) {
//                    //System.out.println("startDTO="+startDTO);
//                    long firstTimestamp = startDTO.getDownLiveTime();
//                    long timeTransfer = TimeDealUtil.timeTransfer(startDTO.getStartTimeStr());
//                    long downTime = timeTransfer - firstTimestamp;
//                    startDTO.setDownTime(calActDownTime(downTime));
//                }else if(startDTO.getNeverStartTime()>0){
//
//                    long timeTransfer = TimeDealUtil.timeTransfer(startDTO.getStartTimeStr());
//                    long downTime = timeTransfer - startDTO.getNeverStartTime();
//                    startDTO.setDownTime(calActDownTime(downTime));
//                }
//                if (stringLongMap.get("lastLiveTime")!=null){
//                    long startDate=stringLongMap.get("lastLiveTime");
//                    long endDate=TimeDealUtil.timeTransfer(startDTO.getStartTimeStr());
//                    if (startDate-endDate==0){
//                        calSecnods(startDate,startDTO,stringLongMap);
//
//                    }
//
//                }

                System.out.println(startDTO.getInstance() + ", " + startDTO.getBusiness2() +
                        ", 宕机时间1: " + startDTO.getDownTime() +
                        ", 宕机次数1: " + startDTO.getDownNum()+
                        ", 启动时间1: " + startDTO.getStartTimeStr()
                );
                calList.add(StartDTO.builder().instance(startDTO.getInstance())
                        .business2(startDTO.getBusiness2())
                        .downTime(startDTO.getDownTime())
                        .downNum(startDTO.getDownNum())
                        .startTimeStr(startDTO.getStartTimeStr())
                        .build());
            } catch (Exception e) {
                System.out.println(e);
            }

        }
        System.out.println("***********************************************************************************************************");
        System.out.println("Instance,Business2" +
                ", 宕机时间 "+
                ", 宕机次数 "+
                ", 启动时间 "

        );
        calList.forEach(startDTO->{
            System.out.println(startDTO.getInstance() + ", " + startDTO.getBusiness2() +
                    "," + startDTO.getDownTime() +
                    "," + startDTO.getDownNum()+
                    "," + startDTO.getStartTimeStr()

            );
        });
        //************************
        // calStartCount(instanceList,startTime);
    }

    public static void calDownTimeBySeconds(String startTime,String lastStartTime,StartDTO startDTO,List<Map<String, Long>> lists){

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.parse(lastStartTime, formatter);
        LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime cutoffTime = startDateTime.minusMinutes(20);

        while (!endTime.isBefore(startDateTime)) {
            LocalDateTime previousHour = endTime.minusHours(1);

            if (previousHour.isBefore(startDateTime)) {

                break;
            } else {
                //System.out.println(previousHour.format(formatter) + " - " + endTime.format(formatter));
                calSecnods(previousHour.format(formatter),endTime.format(formatter),startDTO,lists);
                endTime = previousHour;
            }
        }
    }

    public static void calSecnods(String startTime,String closeTime,StartDTO startDTO,List<Map<String, Long>> lists){

        // 输出结果
        long originTime=TimeDealUtil.timeTransfer(startTime);

        long endTime=TimeDealUtil.timeTransfer(closeTime);

        String query1 = "mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"}";
        String statusUptime = TimeDealUtil.statNommalToDownTime001(url + "/api/v1/query_range?", query1, startDTO.getInstance(), originTime, endTime, 1);
        JSONObject jsonObject2 = JSON.parseObject(statusUptime);
        JSONObject jsonObject21 = jsonObject2.getJSONObject("data");
        JSONArray resultsArray22 = jsonObject21.getJSONArray("result");
        test0014(resultsArray22,startDTO,lists,endTime);
    }


    /**
     * 计算重启的次数
     */
    public static void calStartCount(List<StartDTO> instanceList,String startTime){
        List<StartDTO> instanceList100=new ArrayList<>(10);
        for (StartDTO dto : instanceList) {
            String timeStr = dto.getStartTimeStr();
            if (dto.getStartTimeStr() == null) {
                continue;
            }
            String response1 = getMysqlInstanceList1(TimeDealUtil.timeTransfer(timeStr));
            JSONObject jsonObject100 = JSON.parseObject(response1);
            JSONObject jsonObject2 = jsonObject100.getJSONObject("data");
            JSONArray resultsArray3 = jsonObject2.getJSONArray("result");
            getMysqlInstanceLastStartTime(resultsArray3, startTime,instanceList100);

        }
        // 按 instance 分类统计
        Map<String, List<StartDTO>> instanceMap = instanceList100.stream()
                .collect(Collectors.groupingBy(dto -> dto.getInstance()));
        instanceMap.forEach((instance, dtos) -> {
            System.out.println("Instance: " + instance);
            dtos.forEach(System.out::println);
        });
    }

    public static void calSecnods(long startDate,StartDTO startDTO,Map<String, Long> stringLongMap){


        // 定义日期时间格式
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析日期时间字符串
        LocalDateTime dateTime = LocalDateTime.parse(TimeDealUtil.convertTimestampToDate(startDate), dateTimeFormatter);

        // 获取整点时间
        LocalDateTime startOfHour = dateTime.withMinute(0).withSecond(0);
        LocalDateTime endOfHour = startOfHour.plusHours(1);

        // 输出结果
        long originTime=TimeDealUtil.timeTransfer(startOfHour.format(dateTimeFormatter));

        long endTime=TimeDealUtil.timeTransfer(endOfHour.format(dateTimeFormatter));

        String query1 = "mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"}";
        String statusUptime = TimeDealUtil.statNommalToDownTime001(url + "/api/v1/query_range?", query1, startDTO.getInstance(), originTime, endTime, 1);
        JSONObject jsonObject2 = JSON.parseObject(statusUptime);
        JSONObject jsonObject21 = jsonObject2.getJSONObject("data");
        JSONArray resultsArray22 = jsonObject21.getJSONArray("result");
      //  test0014(resultsArray22,startDTO,stringLongMap);
    }


    /**
     * 递归调用
     * @param startDTO
     * @param currentDate
     * @throws ParseException
     */
    private static void fetchDataRecursively(StartDTO startDTO, Date currentDate, Map<String, Long> stringLongMap,List<Map<String, Long>> list) throws ParseException {


        long originTime = TimeDealUtil.timeTransfer(sdf.format(currentDate))-86400;
        // 加上一天的秒数
        long endTime = TimeDealUtil.timeTransfer(sdf.format(currentDate));

        //STOP_DATE
        if (endTime<STOP_DATE) {
            // System.out.println("Reached stop date without finding lastLiveTime.");
            startDTO.setNeverStartTime(STOP_DATE);
            return; // 到达停止日期,递归结束
        }

        if (originTime<STOP_DATE&&endTime>STOP_DATE) {
            String tempTime=sdf.format(currentDate);
            String[] split = tempTime.split(" ");
            String s = split[0] + " 00:00:00";
            originTime=TimeDealUtil.timeTransfer(s);

        }

        String query1 = "mysql_global_status_uptime{instance=\"" + startDTO.getInstance() + "\"}";
        String statusUptime = TimeDealUtil.statNommalToDownTime001(url + "/api/v1/query_range?", query1, startDTO.getInstance(), originTime, endTime, 60);
        JSONObject jsonObject2 = JSON.parseObject(statusUptime);
        JSONObject jsonObject21 = jsonObject2.getJSONObject("data");
        JSONArray resultsArray22 = jsonObject21.getJSONArray("result");
        test0013(resultsArray22,startDTO,stringLongMap,list,endTime);

        Long lastLiveTime = stringLongMap.get("lastLiveTime");
        if (lastLiveTime != null) {
            System.out.println("Found lastLiveTime: " + lastLiveTime);
            return; // 找到 lastLiveTime,递归结束
        }

        // 向前移动一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.DATE, -1);
        Date newDate = calendar.getTime();

        // 递归调用
        fetchDataRecursively(startDTO, newDate,stringLongMap,list);
    }


    public static void test0014(JSONArray Array,StartDTO startDTO,List<Map<String, Long>> lists,long endTime){

        for (int i = 0; i < Array.size(); i++) {
            JSONObject resultObject = Array.getJSONObject(i);
            JSONObject metricObject = resultObject.getJSONObject("metric");
            // System.out.println("metricObject = " + metricObject);
            String instance = metricObject.getString("instance");
            // System.out.println("instance = " + instance);
            JSONArray valuesArray = resultObject.getJSONArray("values");
            calMysqlServiceRestartTime001(valuesArray,lists,endTime,startDTO);

        }

        return ;
    }

    public static Map<String,Long> test0013(JSONArray Array,StartDTO startDTO,Map<String, Long> map,List<Map<String, Long>> list,long endTime){

        for (int i = 0; i < Array.size(); i++) {
            JSONObject resultObject = Array.getJSONObject(i);
            JSONObject metricObject = resultObject.getJSONObject("metric");
            // System.out.println("metricObject = " + metricObject);
            String instance = metricObject.getString("instance");
            // System.out.println("instance = " + instance);
            JSONArray valuesArray = resultObject.getJSONArray("values");
            List<Long> downtimes = new ArrayList<>();
            calMysqlServiceRestartTime(downtimes,valuesArray,map,startDTO,list,endTime);

        }

        return map;
    }

    /**
     * 查询所有机器的上次重启时间
     * @param resultsArray
     * @param startTime
     */
    public static void getMysqlInstanceLastStartTime(JSONArray resultsArray,String startTime,List<StartDTO> instanceList){

        for (int i = 0; i < resultsArray.size(); i++) {
            JSONObject result = resultsArray.getJSONObject(i);
            JSONObject metric = result.getJSONObject("metric");
            JSONArray value = result.getJSONArray("value");
            if (value==null){
                continue;
            }
            // System.out.println("value = " + value);
            String instance = metric.getString("instance");
            String business2 = metric.getString("business2");
            Long timestamp = value.getLong(0);
            Long uptimeSeconds = value.getLong(1);
            String endTime=TimeDealUtil.dealTime1(timestamp);
            //使用开始时间和截止时间计算整个时间周期是多少
            long transferTime = TimeDealUtil.transferTime(startTime, endTime);
            if (uptimeSeconds<transferTime){
                StartDTO startDTO = TimeDealUtil.calRestartTime(uptimeSeconds, endTime);
                instanceList.add(StartDTO.builder().startTimeSeconds(startDTO.getStartTimeSeconds()).instance(instance)
                        .endTime(endTime)
                        .business2(business2)
                        .uptimeSeconds(uptimeSeconds)
                        .startTimeStr(startDTO.getStartTimeStr()).build());
            }else {
                instanceList.add(StartDTO.builder().instance(instance)
                        .business2(business2)
                        .downTime("2024-05-23 00:00:00~2024-07-01 00:00:00没有宕机")
                        .build());
            }
        }
    }

    public  static String getMysqlInstanceList1(long endTime){
        RestTemplate restTemplate = new RestTemplate();
        // 创建 HttpHeaders 对象
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIwMzUzNTgwNTQsImlzcyI6Imh0dHA6Ly9hbGliYWJhY2xvdWQuY29tIiwiaWF0IjoxNzE5OTk4MDU0LCJqdGkiOiIzZTMzYzc5ZS1kNjE2LTQzNmEtOWNjNi04MjU2NjlkOWVkOGYifQ.R8HP2xIDHh6fYLXIFnPmekzTfre3J3Npxdq67jsMqos");
        headers.set("Accept-Charset", "UTF-8");  // 设置 Accept-Charset header
        // 创建 HttpEntity 对象,并将 HttpHeaders 传递进去
        HttpEntity<String> entity = new HttpEntity<>(headers);

        // 发送 GET 请求,并传递 HttpEntity
        ResponseEntity<String> response = restTemplate.exchange(
                url+"/api/v1/query?query=mysql_global_status_uptime&time="+endTime,
                HttpMethod.GET,
                entity,
                String.class
        );
        // 获取响应体
        String responseBody = response.getBody();
        return responseBody;
    }


    /**
     * 计算mysql服务的重启消耗时间
     */
    public static void calMysqlServiceRestartTime001(JSONArray valuesArray,List<Map<String, Long>> lists,long endTime
            ,StartDTO startDTO){

        long lastUptime = valuesArray.getJSONArray(0).getLong(1);

        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
            long currentUptime = valuePair.getLong(0);
            long value = valuePair.getLong(1);

            if (value<lastUptime){
                JSONArray valuePair1 = valuesArray.getJSONArray(j-1);
                long currentUptime1 = valuePair1.getLong(0);
                long value1 = valuePair1.getLong(1);
                System.out.println("上次时间:"+convertTimestampToDate(currentUptime1)+",已运行时间="+value1);
                System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                long reStartTime=currentUptime-currentUptime1;
                System.out.println("宕机时间="+calActDownTime(reStartTime));
               if (reStartTime!=0){
                   Map<String,Long> longMap=new HashMap<>(16);
                   longMap.put("lastLiveTime",currentUptime1);
                   longMap.put("upTime",value1);
                   longMap.put("downLiveTime",reStartTime);
                   lists.add(longMap);
               }
                break;

            }else if (j==valuesArray.size() - 1){

                long reStartTime=endTime-currentUptime;
                if (reStartTime>0){
                    System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                    System.out.println("截止时间:"+convertTimestampToDate(endTime));
                    QueryUpTimeBySecondUtil.calSecnods(currentUptime,startDTO,lists);
                }

            }

        }

    }

    /**
     * 适用于2024-05-23 19:43:27这种格式的
     * @param timestamp
     * @return
     */
    public static String convertTimestampToDate(long timestamp) {
        // 创建一个 SimpleDateFormat 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置时区
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 例如设置为中国时区

        // 创建一个 Date 对象
        Date date = new Date(timestamp * 1000); // 时间戳是以秒为单位,所以乘以1000转换为毫秒

        // 格式化日期
        return sdf.format(date);
    }

    /**
     * 计算mysql服务的重启消耗时间
     */
    public static void calMysqlServiceRestartTime(List<Long> downtimes,JSONArray valuesArray,Map<String,Long> map,StartDTO startDTO
            ,List<Map<String, Long>> list,long endTime){

        long lastUptime = valuesArray.getJSONArray(0).getLong(1);

        for (int j = 0; j < valuesArray.size(); j++) {
            JSONArray valuePair = valuesArray.getJSONArray(j);
            long currentUptime = valuePair.getLong(0);
            long value = valuePair.getLong(1);

            if (value<lastUptime){
                JSONArray valuePair1 = valuesArray.getJSONArray(j-1);
                long currentUptime1 = valuePair1.getLong(0);
                long value1 = valuePair1.getLong(1);
                System.out.println("上次时间:"+convertTimestampToDate(currentUptime1)+",已运行时间="+value1);
                System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                long reStartTime=currentUptime-currentUptime1;
                System.out.println("宕机时间="+calActDownTime(reStartTime));
                //startDTO.setDownTime(calActDownTime(reStartTime));
                if (reStartTime!=0){
                    Map<String,Long> longMap=new HashMap<>(16);
                    longMap.put("lastLiveTime",currentUptime1);
                    longMap.put("upTime",value1);
                    longMap.put("downLiveTime",reStartTime);
                    list.add(longMap);
                }
                break;

            }else if (j==valuesArray.size() - 1){

                long reStartTime=endTime-currentUptime;

                if (reStartTime>0){
                    System.out.println("当前时间:"+convertTimestampToDate(currentUptime)+",已运行时间="+value);
                    System.out.println("截止时间:"+convertTimestampToDate(endTime));
                    System.out.println("数据中断宕机时间="+calActDownTime(reStartTime));
                    QueryUpTimeBySecondUtil.calSecnods(currentUptime,startDTO,list);
                }

            }

        }

    }


    /**
     * 这里拿到的是服务器无指标的时间
     * @param resultArray
     * @param startDTO
     */
    public static void test0031(JSONArray resultArray,StartDTO startDTO){

        for (int k = 0; k < resultArray.size(); k++) {
            JSONObject resultObject = resultArray.getJSONObject(k);

            JSONObject metricObject = resultObject.getJSONObject("metric");

            JSONArray values = resultObject.getJSONArray("values");
            //**********************************
            // 获取第一条记录的时间戳
            //2024-07-03 17:35:00
            long firstTimestamp = values.getJSONArray(0).getLong(0);
            System.out.println("firstTimestamp = " + firstTimestamp);
            long timeTransfer = TimeDealUtil.timeTransfer(startDTO.getStartTimeStr());
            System.out.println("timeTransfer = " + timeTransfer);
            long downTime = timeTransfer - firstTimestamp;
            System.out.println("downTime = " + downTime);

            if (downTime<=0){
                downTime=timeTransfer-startDTO.getDownLiveTime();
                System.out.println("第一个downTime = " + downTime);
                startDTO.setDownTime(calActDownTime(downTime));
            }else if (downTime>300){
                long calDownTimeByLiveTime=timeTransfer-startDTO.getDownLiveTime();
                System.out.println("calDownTimeByLiveTime = " + calDownTimeByLiveTime);
                if (downTime<calDownTimeByLiveTime){
                    startDTO.setDownTime(calActDownTime(downTime));
                }else if (calDownTimeByLiveTime>0){
                    startDTO.setDownTime(calActDownTime(calDownTimeByLiveTime));
                }else {

                    calSecnods(firstTimestamp,startDTO,null);

                }
                System.out.println("第二个宕机时间 = " + downTime);

            }else {
                System.out.println("第三个downTime = " + downTime);
                startDTO.setDownTime(calActDownTime(downTime));
            }

        }

    }

    public static String calActDownTime(long time){
        if (time==0){
            return "0";
        }
        if (time<60){
            return time+"秒";
        }
        long l = time / 60;
        if (l*60==time){
            return l+"分钟";
        }
        long l1 = time-l * 60;
        return l+"分钟"+l1+"秒";

    }

    /**
     * 将秒数转换为小时、分钟和秒数的方法
     * @param totalSeconds
     * @return
     */
    public static String convertSecondsToTime(long totalSeconds) {

        long hours = totalSeconds / 3600; // 计算小时数
        long remainingSecondsAfterHours = totalSeconds % 3600;

        long minutes = remainingSecondsAfterHours / 60; // 计算分钟数
        long seconds = remainingSecondsAfterHours % 60; // 计算剩余秒数

        return hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒";
    }


    /**
     * 统计服务宕机时间
     */
    public static String queryFirstDownTime(String baseUrl, String query, long start, long end, int step){
        // 1. 设置 RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 2. 创建 HttpHeaders 并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        // 如果有其他请求头,继续设置
        headers.set("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjIwMzUzNTgwNTQsImlzcyI6Imh0dHA6Ly9hbGliYWJhY2xvdWQuY29tIiwiaWF0IjoxNzE5OTk4MDU0LCJqdGkiOiIzZTMzYzc5ZS1kNjE2LTQzNmEtOWNjNi04MjU2NjlkOWVkOGYifQ.R8HP2xIDHh6fYLXIFnPmekzTfre3J3Npxdq67jsMqos");
        // 设置 Accept-Charset header
        headers.set("Accept-Charset", "UTF-8");
        // 3. 创建 HttpEntity 并将 HttpHeaders 设置到其中
        HttpEntity<String> entity = new HttpEntity<>(headers);
        URI uri = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("query", query)
                .queryParam("start", start)
                .queryParam("end", end)
                .queryParam("step", step+"s")
                .build()
                .encode()
                .toUri();

        // 5. 使用 RestTemplate 发送请求并接收响应
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);

        // 6. 返回响应结果
        return response.getBody();

    }

}

  数据验证请以生产数据为准

标签:String,宕机,普罗米修斯,System,long,API,println,startDTO,out
From: https://www.cnblogs.com/q202105271618/p/18343613

相关文章

  • 使用react+node调用科大讯飞api实现实时语音听写(流式版)
    前言--踩坑过程一时间心血来潮,想用科大讯飞的api来做一个语音实时转文字,也是走了很多弯路,边写边查边生成,最后算是完成了。功能实现了但是没有做UI。本来想试试光靠不要服务端光靠前端直接调用科大讯飞的api来实现,但是发现太慢了,四五秒才蹦出来一个字。然后没办法,搭建了一个......
  • 邮件推送api接口的功能优势?有哪些特点?
    邮件推送api接口稳定性如何评估?怎么选邮件API接口?企业和组织依赖邮件推送API接口来实现高效、精准的电子邮件发送。邮件推送API接口提供了一系列强大功能,使企业能够更好地与客户沟通,提升业务效率和客户满意度。AokSend将详细探讨邮件推送API接口的功能优势。邮件推送api接口......
  • Python中的Web开发与API设计
    Python中的Web开发与API设计一、开篇:启航PythonWeb开发之旅1.1Python:不仅仅是脚本语言,更是Web开发的明星1.2Web开发的魔法森林:从静态到动态的转变二、基础篇:PythonWeb开发的基石2.1HTTP协议:互联网通信的通用语言2.2Flask框架:轻装上阵的小巧之选2.3Django框架:全......
  • Linux系统内存管理API
    Linux系统内存管理API遵循POSIX标准的内存管理API:#include<unistd.h>​//brk和sbrk在内部维护一个指针p(void*),p指针指向当前堆内存中已经映射成功的最后一个字节的下一个地址位置void*sbrk(intptr_tincrement);功能:根据参数increment来调整p的位置,既可以映射内存,也......
  • 身份证OCR识别API
    身份证OCR识别API是一种能够自动识别身份证上文字信息的技术,广泛应用于需要快速录入身份证信息的业务场景中。目前,市场上有多家公司提供这项服务,包括微信、腾讯云、华为云和阿里云等。微信的身份证OCR识别接口支持小程序调用,能够识别身份证正反面的所有字段,如姓名、性别、民族......
  • Jenkins API用户认证方式
    1、概述Jenkins的API可以通过用户名+密码或者用户名+Token的方式来进行认证,这篇文章以具体示例来说明具体的使用方式。2、Jenkins环境本文示例基于Jenkins2.452.3版本进行演示,详细的环境构建可参考《Centos7下安装配置最新版本Jenkins(2.452.3)》这篇博文。3、Jenkin......
  • windows C++-通过 C++/WinRT 使用 API(三)
    统一构造在C++/WinRT版本2.0及更高版本中,有一种优化的构造形式可供你使用,它被称作“统一构造”(请参见C++/WinRT2.0中的新增功能和更改)。若要使用统一构造而不是winrt::make,你需要一个激活工厂。要生成激活工厂,一种好的方式是向IDL添加构造函数。//MainPage.idl......
  • windows C++-通过 C++/WinRT 使用 API(二)
    延迟初始化在C++/WinRT中,每个类型都有一个特殊的C++/WinRTstd::nullptr_t构造函数。除了该构造函数,所有其他类型的构造函数(包括默认的构造函数)都会导致系统创建一个支持的Windows运行时对象,并为你提供它的智能指针。因此,该规则适用于使用默认构造函数的任何地方,例如......
  • 深入剖析:Apache Flink的Table API与SQL API之差异
    在当今的大数据处理领域,ApacheFlink以其卓越的流处理能力而广受关注。Flink提供了多种API来满足不同场景下的数据流处理需求,其中TableAPI和SQLAPI是两种非常关键的接口。本文将深入探讨这两种API的特点、使用场景以及它们之间的主要区别,并通过少量示例代码来展示它们的应......
  • webpack HMR API解析
    介绍一下webpackhmr相关的APIwebpack首先将模块变成对象的一个属性,该属性是一个方法,调用它就返回最新的模块。模块的变更就变成了更新这些方法的定义。其次,webpack对于我们代码的import,做了拦截,会变成从它的模块对象里面去读取模块,同时它做了缓存。最后,当模块变化的时候,它会依......