Spring Boot实现监控linux-cpu和内存使用情况,并发送邮件
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot实现监控linux-cpu和内存使用情况,并发送邮件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考自:https://blog.csdn.net/qq_42035966/article/details/81332554
一.主要功能
監控linux的cpu和內存使用率,當頻率過高時,發送郵件提醒功能。
二.代碼
(1)導入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>(2)配置文件
spring:mail:host: xxxusername: xxxpassword: xxxport: 465properties:mail.smtp.auth: truemail.smtp.ssl.enable: truemail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactorymail.smtp.socketFactory.port: 465(3)工具類
public class OSUtils {/*** 功能:獲取Linux系統cpu使用率*/public static float cpuUsage() {try {Map<?, ?> map1 = OSUtils.cpuinfo();Thread.sleep(5 * 1000);Map<?, ?> map2 = OSUtils.cpuinfo();long user1 = Long.parseLong(map1.get("user").toString());long nice1 = Long.parseLong(map1.get("nice").toString());long system1 = Long.parseLong(map1.get("system").toString());long idle1 = Long.parseLong(map1.get("idle").toString());long user2 = Long.parseLong(map2.get("user").toString());long nice2 = Long.parseLong(map2.get("nice").toString());long system2 = Long.parseLong(map2.get("system").toString());long idle2 = Long.parseLong(map2.get("idle").toString());long total1 = user1 + system1 + nice1;long total2 = user2 + system2 + nice2;float total = total2 - total1;long totalIdle1 = user1 + nice1 + system1 + idle1;long totalIdle2 = user2 + nice2 + system2 + idle2;float totalidle = totalIdle2 - totalIdle1;float cpusage = (total / totalidle) * 100;System.out.println("cpu使用率:" + cpusage + "%");return cpusage;} catch (InterruptedException e) {e.printStackTrace();}return 0;}/*** 功能:CPU使用信息*/public static Map<?, ?> cpuinfo() {InputStreamReader inputs = null;BufferedReader buffer = null;Map<String, Object> map = new HashMap<String, Object>();try {inputs = new InputStreamReader(new FileInputStream("/proc/stat"));buffer = new BufferedReader(inputs);String line = "";while (true) {line = buffer.readLine();if (line == null) {break;}if (line.startsWith("cpu")) {StringTokenizer tokenizer = new StringTokenizer(line);List<String> temp = new ArrayList<String>();while (tokenizer.hasMoreElements()) {String value = tokenizer.nextToken();temp.add(value);}map.put("user", temp.get(1));map.put("nice", temp.get(2));map.put("system", temp.get(3));map.put("idle", temp.get(4));map.put("iowait", temp.get(5));map.put("irq", temp.get(6));map.put("softirq", temp.get(7));map.put("stealstolen", temp.get(8));break;}}} catch (Exception e) {e.printStackTrace();} finally {try {buffer.close();inputs.close();} catch (Exception e2) {e2.printStackTrace();}}return map;}/*** 功能:內存使用率*/public static long memoryUsage() {Map<String, Object> map = new HashMap<String, Object>();InputStreamReader inputs = null;BufferedReader buffer = null;try {inputs = new InputStreamReader(new FileInputStream("/proc/meminfo"));buffer = new BufferedReader(inputs);String line = "";while (true) {line = buffer.readLine();if (line == null)break;int beginIndex = 0;int endIndex = line.indexOf(":");if (endIndex != -1) {String key = line.substring(beginIndex, endIndex);beginIndex = endIndex + 1;endIndex = line.length();String memory = line.substring(beginIndex, endIndex);String value = memory.replace("kB", "").trim();map.put(key, value);}}long memTotal = Long.parseLong(map.get("MemTotal").toString());System.out.println("內存總量" + memTotal + "KB");long memFree = Long.parseLong(map.get("MemFree").toString());System.out.println("剩余內存" + memFree + "KB");long memused = memTotal - memFree;System.out.println("已用內存" + memused + "KB");long buffers = Long.parseLong(map.get("Buffers").toString());long cached = Long.parseLong(map.get("Cached").toString());double usage = (double) (memused - buffers - cached) / memTotal * 100;System.out.println("內存使用率" + usage + "%");return memFree;} catch (Exception e) {e.printStackTrace();} finally {try {buffer.close();inputs.close();} catch (Exception e2) {e2.printStackTrace();}}return 0;}/*** 主入口** @param args*/public static void main(String[] args) {//1. 創建計時器類Timer timer = new Timer();//2. 創建任務類TimerTask task = new TimerTask() {@Overridepublic void run() {//cup使用率float cpuUsage = cpuUsage();System.out.println(cpuUsage); // if(cpuUsage > 10.0 ){ // SendMail.sendMail("xxxxx@qq.com", "服務器cpu使用率過高,請注意查看", "服務器提醒"); // }//內存使用情況long memoryUsage = memoryUsage(); // if((memoryUsage/1024) < 100){ // SendMail.sendMail("xxxxx@qq.com","服務器內存剩余空間不足,請注意查看", "服務器提醒"); // }System.out.println(memoryUsage);}};timer.schedule(task, 1000, 1000 * 10);}} /*** 定時監控CPU和內存使用率(異常則發送郵件)*/@Scheduled(cron = "0 */1 * * * ?")public void monitorCPU() {logger.info("定時監控CPU和內存使用率任務開啟");float cpuUsage = OSUtils.cpuUsage();logger.info("cpuUsage:" + cpuUsage);if (cpuUsage > 70.0) {emailService.sendSimpleEmail("583509857@qq.com", "服務器cpu使用率過高,請注意查看", "拳秀體育:服務器提醒:" + wechatTransfer.getIp());}long memoryUsage = OSUtils.memoryUsage();logger.info("memoryUsage:" + memoryUsage);if ((memoryUsage / 1024) < 100) {emailService.sendSimpleEmail("583509857@qq.com", "服務器內存剩余空間不足,請注意查看", "拳秀體育:服務器提醒:" + wechatTransfer.getIp());}}啟動類中添加
@EnableScheduling注解(4)發送郵件定時任務(每分鐘允許一次)
@Component public class EmailService {@Autowiredprivate JavaMailSender javaMailSender;@Value("${spring.mail.username}")private String sender;public synchronized void sendSimpleEmail(String email, String title, String text) {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setFrom(sender);mailMessage.setTo(email);mailMessage.setSubject(title);mailMessage.setText(text);javaMailSender.send(mailMessage);}}?
總結
以上是生活随笔為你收集整理的Spring Boot实现监控linux-cpu和内存使用情况,并发送邮件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Cloud(八)使用Zip
- 下一篇: java并发编程之Semaphore