参考自: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和内存使用情况,并发送邮件相关推荐

  1. Spring Boot 应用监控:Actuator与 Admin

    第 III 部分Spring Boot 系统监控.测试与运维 Spring Boot 应用监控:Actuator与 Admin <Spring Boot 实战开发>(陈光剑) -- 基于 ...

  2. 高级版的 jvisualvm :Spring Boot Admin 监控 Spring Boot 微服务项目

    前奏:先说一下 Java VisualVM Java VisualVM 是一个能够监控 JVM 的 jdk 自带的图形化工具: 在 $JAVA_HOME/bin 目录下,可直接运行它. 要想监控远程服 ...

  3. Spring Boot应用监控实战

    概述 之前讲过Docker容器的可视化监控,即监控容器的运行情况,包括 CPU使用率.内存占用.网络状况以及磁盘空间等等一系列信息.同样利用SpringBoot作为微服务单元的实例化技术选型时,我们不 ...

  4. top 命令_Linux监控cpu以及内存使用情况之top命令

    top命令是Linux下常用的性能分析工具,比如cpu.内存的使用,能够实时显示系统中各个进程的资源占用状况,类似于Windows的任务管理器. top显示系统当前的进程和其他状况,是一个动态显示过程 ...

  5. Linux查看CPU和内存使用情况(ps、free、htop、atop、nmon、/proc/meminfo等)

    文章目录 Linux查看CPU和内存使用情况 Linux查看CPU和内存命令:ps 查看系统内存命令:free free与available的区别 htop (推荐) 安装 htop 参数 常用 界面 ...

  6. 使⽤用 Spring Boot Actuator 监控应⽤

    1.美图 2.概述 微服务的特点决定了功能模块的部署是分布式的,⼤部分功能模块都是运行在不同的机器上,彼此通过服务调⽤进行交互,前后台的业务流会经过很多个微服务的处理和传递,出现异常如何快速定位便成为 ...

  7. Shell 脚本来监控 Linux 系统的内存

    一.安装Linux下面的一个邮件客户端Msmtp软件(类似于一个Foxmail的工具) 1.下载安装:http://downloads.sourceforge.net - 206451&big ...

  8. Linux系统快速查看CPU和内存使用情况,附各参数详解

    Linux系统中查看CPU和内存使用情况,是一个运维工程师常见的事情,下面分享一下. 目 录 1.top命令 2.ps命令 3.free命令 1.top命令 top命令是Linux下常用的性能分析工具 ...

  9. Linux查看应用的CPU、内存使用情况

    目录 一.jps命令. 二.ps命令. 三.top命令. 四.free命令. 五.df命令. 查看应用的CPU.内存使用情况,使用jps.ps.top.free.df命令查看. 一.jps命令. 可以 ...

  10. Spring Boot Actuator监控页面报错解决

    今天在访问Spring Boot Actuator监控页面的时候报错了,之前都没遇到这种情况,大概的意思就是无权限访问 <html><body><h1>Whitel ...

最新文章

  1. zlib和openssl相关库错误的解决
  2. 该不该放弃单片机,嵌入式这条路?
  3. Firefox鼠标手势插件在哪安装 火狐浏览器鼠标手势怎么用
  4. wifi管理系统_如何有效选择一款移动考勤管理系统
  5. 【ELK】ELK安装与配置
  6. linux服务器配置jdk1.8
  7. Xcode下的中文乱码问题
  8. XManager连接CentOS6.5
  9. web网页设计实例作业 ——校园文化(7页) html大学生网站开发实践作业
  10. 工资计算系统设计实现
  11. AGV控制器的国产化之路
  12. 在Word中使用EndNote插入参考文献
  13. 我爱你——再高级一点
  14. android 5.0rom官方,Android 5.0刷机包开放下载 升级需谨慎
  15. wampserver安装错误 应用程序无法正常启动0xc000007b解决方法
  16. 网络安全策略管理架构
  17. 计算机组成原理课后答案(唐朔飞第二版)
  18. 让你眼前一亮的3. Tomcat 性能调优 (值得收藏)
  19. 2018-07-13心情日记
  20. IDC服务器运维常见命令

热门文章

  1. 2022年美国大学生数学建模竞赛——Problem C:交易策略
  2. lower_bound和 upper_bound 用法(STL)
  3. JDK的安装与环境变量配置
  4. ICS汇编学习笔记——8086中的寄存器
  5. 网络互连基础——笔记
  6. 2017 年热门编程语言排行榜,你的语言上榜没?
  7. 移动重定位表到新增节
  8. angr学习笔记(3)
  9. 脚本类恶意程序分析技巧汇总
  10. 【Laravel】连接sqlite,Database [] not configured,sqlite example