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

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

查询服务上次启动时间

使用/api/v1/query_range

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

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

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

具体代码如下

pom文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
<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>

  工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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+"秒";
 
    }
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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);
    }
 
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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);
                }
            }
 
        }
 
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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();
 
    }
 
}

  实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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;
}

主类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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();
 
    }
 
}

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

posted @   不忘初心2021  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
· 用 C# 插值字符串处理器写一个 sscanf
点击右上角即可分享
微信分享提示