许鹏程
2023-05-24 34ff70bc904e68548b5996561d5da52a67a46d24
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
package com.product.admin.util;
 
import cn.hutool.core.util.NumberUtil;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.sun.management.OperatingSystemMXBean;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Component
public class MonitorInfoUtil extends Thread {
    static List<MonitorInfoBean> monitorInfoBeanList = new ArrayList<>();
 
    public List<MonitorInfoBean> getMonitorInfoBeanList() {
        return this.monitorInfoBeanList;
    }
 
    public void removeMonitorInfoList() {
        monitorInfoBeanList.clear();
    }
 
    @PostConstruct
    private void runThread() {
        this.start();
    }
 
 
    public void run() {
        while (true) {
            try {
                IMonitorService service = new MonitorServiceImpl();
                MonitorInfoBean monitorInfo = service.getMonitorInfoBean();
//                System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
//            System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());
////        System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
//            System.out.println("操作系统=" + monitorInfo.getOsName());
//            System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "GB");
//            System.out.println("剩余的物理内存=" + monitorInfo.getFreePhysicalMemorySize() + "GB");
//            System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "GB");
//            System.out.println("线程总数=" + monitorInfo.getTotalThread());
//            System.out.println("内存使用率=" + monitorInfo.getMemoryRate() + "%");
//            System.out.println(monitorInfoBeanList.size());
                synchronized (monitorInfoBeanList) {
                    this.monitorInfoBeanList.add(monitorInfo);
                    while (this.monitorInfoBeanList.size() > 20) {
                        this.monitorInfoBeanList.remove(0);
                    }
                }
                Thread.sleep(5000);
            } catch (Exception e) {
                SpringMVCContextHolder.getSystemLogger().error(e);
            }
        }
 
    }
 
    /**
     * 获取系统各个硬盘的总容量、已经使用的容量、剩余容量和使用率
     *
     * @throws IOException
     */
    public static List<Map<String, Object>> getDiskInfo() {
        DecimalFormat df = new DecimalFormat("#0.00");
        File[] disks = File.listRoots();
        List<Map<String, Object>> result = new ArrayList<>();
        for (File file : disks) {
            // 获取总容量
            long totalSpace = file.getTotalSpace();
            if (totalSpace == 0L) {
                continue;
            }
            // 获取剩余容量
            long usableSpace = file.getUsableSpace();
            // 获取已经使用的容量
            long freeSpace = totalSpace - usableSpace;
            // 获取使用率
            float useRate = (float) ((freeSpace * 1.0 / totalSpace) * 100);
//            SpringMVCContextHolder.getSystemLogger().error("总容量: " + transformation(totalSpace));
//            SpringMVCContextHolder.getSystemLogger().error("已经使用: " + transformation(freeSpace));
//            SpringMVCContextHolder.getSystemLogger().error("剩余容量: " + transformation(usableSpace));
//            SpringMVCContextHolder.getSystemLogger().error("使用率: " + Double.parseDouble(df.format(useRate)) + "%   ");
            Map<String, Object> map = new HashMap<>();
            map.put("totalCapacity", transformation(totalSpace));
            map.put("useCapacity", transformation(freeSpace));
            map.put("surplusCapacity", transformation(usableSpace));
            map.put("useRate", Double.parseDouble(df.format(useRate)));
            try {
                //盘符
                map.put("drive", file.getCanonicalPath().replace(":", "").replaceAll("\\\\", ""));
            } catch (Exception e) {
                continue;
            }
            result.add(map);
 
 
        }
        return result;
    }
 
    /**
     * 将字节容量转化为GB
     */
    public static double transformation(long size) {
        return NumberUtil.round(size / 1024.00 / 1024.00 / 1024.00, 2).doubleValue();
    }
 
    public static class MonitorInfoBean {
        private List<Map<String, Object>> diskInfo;
 
        private int availableProcessors;
        /**
         * 剩余内存.
         */
        private double freeMemory;
        /**
         * 操作系统.
         */
        private String osName;
        /**
         * 总的物理内存.
         */
        private double totalMemorySize;
        /**
         * 剩余的物理内存.
         */
        private double freePhysicalMemorySize;
        /**
         * 已使用的物理内存.
         */
        private double usedMemory;
        /**
         * 线程总数.
         */
        private int totalThread;
        /**
         * cpu使用率.
         */
        private double cpuRatio;
 
        private double memoryRate;
 
        private String time;
 
        public int getAvailableProcessors() {
            return Runtime.getRuntime().availableProcessors();
        }
 
        public List<Map<String, Object>> getDiskInfo() {
            return diskInfo;
        }
 
        public void setDiskInfo(List<Map<String, Object>> diskInfo) {
            this.diskInfo = diskInfo;
        }
 
        public double getMemoryRate() {
            return NumberUtil.round(NumberUtil.div(usedMemory, totalMemorySize) * 100, 2).doubleValue();
        }
 
        public void setMemoryRate(double memoryRate) {
            this.memoryRate = memoryRate;
        }
 
        public String getTime() {
            return time;
        }
 
        public void setTime(String time) {
            this.time = time;
        }
 
        public double getFreeMemory() {
            return freeMemory;
        }
 
        public void setFreeMemory(double freeMemory) {
            this.freeMemory = freeMemory;
        }
 
        public double getFreePhysicalMemorySize() {
            return freePhysicalMemorySize;
        }
 
        public void setFreePhysicalMemorySize(double freePhysicalMemorySize) {
            this.freePhysicalMemorySize = freePhysicalMemorySize;
        }
 
        public String getOsName() {
            return osName;
        }
 
        public void setOsName(String osName) {
            this.osName = osName;
        }
 
        public double getTotalMemorySize() {
            return totalMemorySize;
        }
 
        public void setTotalMemorySize(double totalMemorySize) {
            this.totalMemorySize = totalMemorySize;
        }
 
        public int getTotalThread() {
            return totalThread;
        }
 
        public void setTotalThread(int totalThread) {
            this.totalThread = totalThread;
        }
 
        public double getUsedMemory() {
            return usedMemory;
        }
 
        public void setUsedMemory(double usedMemory) {
            this.usedMemory = usedMemory;
        }
 
        public double getCpuRatio() {
            return cpuRatio;
        }
 
        public void setCpuRatio(double cpuRatio) {
            this.cpuRatio = cpuRatio;
        }
    }
 
    //之后,建立bean的接口
 
    public interface IMonitorService {
        public MonitorInfoBean getMonitorInfoBean();
    }
 
    //然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。
 
 
    /**
     * 获取系统信息的业务逻辑实现类.
     */
    public static class MonitorServiceImpl implements IMonitorService {
        private static final int CPUTIME = 30;
        private static final int PERCENT = 100;
        private static final int FAULTLENGTH = 10;
        private static final File versionFile = new File("/proc/version");
        private static String linuxVersion = null;
 
        /**
         * 获得当前的监控对象.
         *
         * @return 返回构造好的监控对象
         * @throws Exception
         */
        public MonitorInfoBean getMonitorInfoBean() {
            OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
                    .getOperatingSystemMXBean();
            // 操作系统
            String osName = System.getProperty("os.name");
            // 总的物理内存
            double totalMemorySize = transformation(osmxb.getTotalPhysicalMemorySize());
//            System.out.println("计算总的物理内存耗时:" + timer.intervalMs() + "ms");
            // 剩余的物理内存
            double freePhysicalMemorySize = transformation(osmxb.getFreePhysicalMemorySize());
            // 已使用的物理内存
            double usedMemory = transformation((osmxb.getTotalPhysicalMemorySize() - osmxb
                    .getFreePhysicalMemorySize()));
            // 获得线程总数
            ThreadGroup parentThread;
            for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
                    .getParent() != null; parentThread = parentThread.getParent())
                ;
            int totalThread = parentThread.activeCount();
 
            double cpuRatio = new BigDecimal(osmxb.getSystemCpuLoad() * 100).setScale(2, RoundingMode.HALF_UP).doubleValue();
            List<Map<String, Object>> diskInfo = getDiskInfo();
            // 构造返回对象
            MonitorInfoBean infoBean = new MonitorInfoBean();
            infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
            infoBean.setOsName(osName);
            infoBean.setTotalMemorySize(totalMemorySize);
            infoBean.setTotalThread(totalThread);
            infoBean.setUsedMemory(usedMemory);
            infoBean.setCpuRatio(cpuRatio);
            infoBean.setDiskInfo(diskInfo);
            LocalTime now2 = LocalTime.now();
            infoBean.setTime(now2.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            return infoBean;
        }
 
 
    }
 
    //  其中,Bytes类用来处理字符串
    public static class Bytes {
        public static String substring(String src, int start_idx, int end_idx) {
            byte[] b = src.getBytes();
            String tgt = "";
            for (int i = start_idx; i <= end_idx; i++) {
                tgt += (char) b[i];
            }
            return tgt;
        }
    }
 
}