Commit 905a0578 authored by chenjian's avatar chenjian

内存检测、CPU检测功能实现

prod开发环境创建
内部服务器环境配置搭建
parent 73c77a52
This diff is collapsed.
package com.ebo.module.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "xxljob.executor.qqemail")
public class QQEmailConfig {
private String toEmail;
private String smtpHost;
private int smtpPort;
private String smtpUser;
private String smtpPass;
}
\ No newline at end of file
package com.ebo.module.task;
import com.ebo.module.utils.GetAccessToken;
import com.ebo.module.utils.SendMessageEmail;
import com.google.gson.Gson;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
@Slf4j
public class CpuMonitorHandler extends IJobHandler {
@Autowired
private SendMessageEmail sendMessageEmail;
private final static String apiUrl = "http://localhost:8659/monitor/server/cpu";
@XxlJob("cpuMonitorJob")
@Override
public void execute() throws Exception {
log.info("Cpu Monitor Job Start");
String accessToken = GetAccessToken.getAccessToken();
if (accessToken == null) {
log.error("获取令牌失败");
return;
}
URIBuilder uriBuilder = new URIBuilder(apiUrl);
uriBuilder.addParameter("access_token", accessToken);
String urlWithParams = uriBuilder.build().toString();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlWithParams);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
Map<String, Object> responseresult = new Gson().fromJson(result, Map.class);
Map<String, Object> data = (Map<String, Object>) responseresult.get("data");
double free = Double.parseDouble(data.get("free").toString());
double threshold = 80; // 设置阈值
if ((100-free) > threshold) {
sendMessageEmail.sendAlert("Cpu内存占用过高警告", "目前内存占用为: " + (100-free) + "%");
} else {
log.info("Cpu内存占用正常: " + (100-free) + "%");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("Cpu Monitor Job End");
}
}
\ No newline at end of file
package com.ebo.module.task;
import com.ebo.module.utils.GetAccessToken;
import com.ebo.module.utils.SendMessageEmail;
import com.google.gson.Gson;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
@Slf4j
public class JvmMonitorHandler extends IJobHandler {
@Autowired
private SendMessageEmail sendMessageEmail;
private final static String apiUrl = "http://localhost:8659/monitor/server/jvm";
@XxlJob("jvmMonitorJob")
@Override
public void execute() throws Exception {
log.info("Jvm Monitor Job Start");
String accessToken = GetAccessToken.getAccessToken();
if (accessToken == null) {
log.error("获取令牌失败");
return;
}
// 构建带有查询参数的 URL
URIBuilder uriBuilder = new URIBuilder(apiUrl);
uriBuilder.addParameter("access_token", accessToken);
String urlWithParams = uriBuilder.build().toString();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlWithParams);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
// 解析响应数据
Map<String, Object> responseresult = new Gson().fromJson(result, Map.class);
Map<String, Object> data = (Map<String, Object>) responseresult.get("data");
log.info("data为{}",data);
double max = Double.parseDouble(data.get("max").toString());
double total = Double.parseDouble(data.get("total").toString());
double jvmUsage = total/max;
double threshold = 90; // 设置阈值
if (jvmUsage > threshold) {
// 发送警报
sendMessageEmail.sendAlert("内存占用过高警告", "目前内存占用为: " + jvmUsage + "%");
} else {
log.info("内存占用正常: " + jvmUsage + "%");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("Jvm Monitor Job End");
}
}
\ No newline at end of file
package com.ebo.module.task;
import com.ebo.module.utils.GetAccessToken;
import com.ebo.module.utils.SendMessageEmail;
import com.google.gson.Gson;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
@Component
@Slf4j
public class MemoryMonitorHandler extends IJobHandler {
@Autowired
private SendMessageEmail sendMessageEmail;
@XxlJob("memoryMonitorJob")
@Override
public void execute() throws Exception {
log.info("Memory Monitor Job Start");
String accessToken = GetAccessToken.getAccessToken();
if (accessToken == null) {
log.error("获取令牌失败");
return;
}
String apiUrl = "http://localhost:8659/monitor/server/mem";
// 构建带有查询参数的 URL
URIBuilder uriBuilder = new URIBuilder(apiUrl);
uriBuilder.addParameter("access_token", accessToken);
String urlWithParams = uriBuilder.build().toString();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(urlWithParams);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
// 解析响应数据
Map<String, Object> responseresult = new Gson().fromJson(result, Map.class);
Map<String, Object> data = (Map<String, Object>) responseresult.get("data");
// 检查内存使用率
double usage = Double.parseDouble(data.get("usage").toString());
double threshold = 80.0; // 设置阈值
if (usage > threshold) {
// 发送警报
sendMessageEmail.sendAlert("内存占用过高警告", "目前内存占用为: " + usage + "%");
} else {
log.info("内存占用正常: " + usage + "%");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("Memory Monitor Job End");
}
}
\ No newline at end of file
package com.ebo.module.utils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Map;
@Slf4j
public class GetAccessToken {
/**
* 以管理员身份跳过认证
* @return
*/
public static String getAccessToken() {
String authUrl = "http://localhost:8659/sys/auth/login";
String username = "guoxianhui";
String password = "guoxianhui2002";
String key = ""; // 如果有 key,填写对应的值
String captcha = ""; // 如果有 captcha,填写对应的值
HttpPost httpPost = new HttpPost(authUrl);
httpPost.setHeader("Content-Type", "application/json");
String json = String.format("{\"username\":\"%s\",\"password\":\"%s\",\"key\":\"%s\",\"captcha\":\"%s\"}",
username, password, key, captcha);
try (CloseableHttpClient httpClient = HttpClients.createDefault();){
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost);){
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String result = EntityUtils.toString(responseEntity);
log.info("Auth Response: " + result);
// 解析响应数据
Map<String, Object> responseMap = new Gson().fromJson(result, Map.class);
Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
return dataMap.get("access_token").toString();
}
}
} catch (IOException e) {
log.error("Failed to get access token", e);
}
return null;
}
}
package com.ebo.module.utils;
import com.ebo.module.config.QQEmailConfig;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Properties;
@Slf4j
@Component
public class SendMessageEmail {
private final QQEmailConfig qqemailConfig;
@Autowired
public SendMessageEmail(QQEmailConfig qqemailConfig) {
this.qqemailConfig = qqemailConfig;
}
public void sendAlert(String subject, String message) {
// 发送邮件
Properties props = new Properties();
props.put("mail.smtp.host", qqemailConfig.getSmtpHost());
props.put("mail.smtp.port", qqemailConfig.getSmtpPort());
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(qqemailConfig.getSmtpUser(), qqemailConfig.getSmtpPass());
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(qqemailConfig.getSmtpUser(), false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(qqemailConfig.getToEmail(), false));
msg.setSubject(subject);
msg.setText(message);
msg.setSentDate(new Date());
Transport.send(msg);
log.info("Alert sent successfully");
} catch (MessagingException e) {
log.info("Failed to send alert", e);
}
}
}
# 预发布环境
spring:
data:
redis:
database: 13
host: 10.18.18.51
port: 6379
password: 123456
timeout: 6000ms # 连接超时时长(毫秒)
datasource:
dynamic:
hikari: # Hikari 连接池全局配置
connection-timeout: 30000 # 等待连接池分配链接的最大时长(毫秒),超过这个时长还没有可用的连接则发生 SQLException,默认:30 秒
minimum-idle: 2 # 最小空闲连接数
maximum-pool-size: 10 # 最大连接数
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10 分钟
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认: 30 分钟
connection-test-query: SELECT 1
primary: master
datasource:
master:
# MySQL8
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/itask?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: Mysql@cyunsing
oms:
# MySQL8
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/itask?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: Mysql@cyunsing
logging:
level:
org:
springframework:
jdbc:
core:
JdbcTemplate: DEBUG
xxl:
job:
enable: true #是否开始任务
admin:
## addresses: http://xxljob.sit.gdyibo.com.cn/xxl-job-admin #xxljob调度中心部署 例如:http://127.0.0.1:8080/xxl-job-admin
addresses: http://10.18.18.68:8080/xxl-job-admin
executor:
appname: orderpt #xxljob配置的执行器名称,
ip: #执行器IP,默认为空表示自动获取IP
port: 9501 #xxljob配置的端口号,默认为9999
logpath: /usr/local/java/ITask/logs #执行器运行日志文件存储磁盘路径
logretentiondays: 15 #调度中心日志表数据保存天数,过期日志自动清理;限制大于等于7时生效,否则, 如-1,关闭自动清理功能
accessToken: Ebo-Token #调度中心通讯TOKEN [选填]:非空时启用
execl:
# outFileTempPath: /Users/gxh/Documents/ybProject/fast-spms3/fast-spms-admin/oms-server/src/main/resources/execlOutTemp
outFileTempPath: /usr/local/java/ITask/execlOutTemp
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
......@@ -4,7 +4,7 @@ spring:
database: 13
host: 127.0.0.1
port: 6379
password: Yb#2021&yb
password: 123456
timeout: 6000ms # 连接超时时长(毫秒)
datasource:
dynamic:
......@@ -20,15 +20,15 @@ spring:
master:
# MySQL8
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://119.23.144.105:3306/fast_order_pt_dev?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: orderdev
password: Orderdev@2099
url: jdbc:mysql://127.0.0.1:3306/itask?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: Mysql@cyunsing
oms:
# MySQL8
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://119.23.144.105:3306/fast_order_pt_dev?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: orderdev
password: Orderdev@2099
url: jdbc:mysql://127.0.0.1:3306/itask?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
username: root
password: Mysql@cyunsing
xxl:
job:
enable: false #是否开始任务
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment