实现第一版服务器监控

pull/217/head
zhanghouying 2019-11-05 13:47:34 +08:00
parent aaa373bdcf
commit 2b6d94f823
38 changed files with 876 additions and 1 deletions

71
eladmin-monitor/pom.xml Normal file
View File

@ -0,0 +1,71 @@
<?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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eladmin-monitor</artifactId>
<version>2.2</version>
<name>客户端监控模块</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hyperic</groupId>
<artifactId>sigar</artifactId>
<version>1.6.5.132</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 跳过单元测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
<excludes>
</excludes>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<excludes>
<exclude>sigar-lib/**</exclude>
</excludes>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,20 @@
package me.zhengjie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
*
* @author: Zhang houying
* @date: 2019/11/3
*/
@EnableAsync
@SpringBootApplication
public class MonitorRun {
public static void main(String[] args) {
SpringApplication.run(MonitorRun.class, args);
}
}

View File

@ -0,0 +1,63 @@
package me.zhengjie.res;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Sigar;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@RestController
@RequestMapping("/api/serverMonitor")
public class ServerMonitorController {
private Sigar sigar = new Sigar();
private static final double GB = 1024*1024*1024.00;
@GetMapping
public ResponseEntity getServerInfo(){
Map<String,Object> resultMap = new HashMap<>(8);
try {
CpuInfo[] infoList = sigar.getCpuInfoList();
resultMap.put("cpuRate",sigar.getCpuPerc().getCombined());
resultMap.put("cpuCore",infoList.length);
resultMap.put("memTotal",sigar.getMem().getTotal()/GB);
resultMap.put("memUsed",sigar.getMem().getUsed()/GB);
FileSystem[] fsArray = sigar.getFileSystemList();
double diskTotal = 0;
double diskUsed = 0;
for (int i = 0; i < fsArray.length; i++) {
try {
FileSystem fs = fsArray[i];
FileSystemUsage usage = null;
usage = sigar.getFileSystemUsage(fs.getDirName());
switch (fs.getType()) {
case 2:
//本地硬盘
diskTotal += usage.getTotal()/GB*1024;
diskUsed += usage.getUsed()/GB*1024;
break;
}
} catch (Exception e) {}
}
resultMap.put("diskTotal",diskTotal);
resultMap.put("diskUsed",diskUsed);
resultMap.put("swapTotal",sigar.getSwap().getTotal()/GB);
resultMap.put("swapUsed",sigar.getSwap().getUsed()/GB);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<>(resultMap, HttpStatus.OK);
}
}

View File

@ -0,0 +1,275 @@
package me.zhengjie.utils;
import org.hyperic.sigar.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Properties;
/**
* @author: ZhangHouYing
* @date: 2019-11-03 15:04
*/
public class SigarUtil {
public static void main(String[] args) {
try {
// System信息从jvm获取
property();
System.out.println("----------------------------------");
// cpu信息
cpu();
System.out.println("----------------------------------");
// 内存信息
memory();
System.out.println("----------------------------------");
// 操作系统信息
os();
System.out.println("----------------------------------");
// 用户信息
who();
System.out.println("----------------------------------");
// 文件系统信息
file();
System.out.println("----------------------------------");
// 网络信息
net();
System.out.println("----------------------------------");
// 以太网信息
ethernet();
System.out.println("----------------------------------");
} catch (Exception e1) {
e1.printStackTrace();
}
}
private static void property() throws UnknownHostException {
Runtime r = Runtime.getRuntime();
Properties props = System.getProperties();
InetAddress addr;
addr = InetAddress.getLocalHost();
String ip = addr.getHostAddress();
Map<String, String> map = System.getenv();
String userName = map.get("USERNAME");// 获取用户名
String computerName = map.get("COMPUTERNAME");// 获取计算机名
String userDomain = map.get("USERDOMAIN");// 获取计算机域名
System.out.println("用户名: " + userName);
System.out.println("计算机名: " + computerName);
System.out.println("计算机域名: " + userDomain);
System.out.println("本地ip地址: " + ip);
System.out.println("本地主机名: " + addr.getHostName());
System.out.println("JVM可以使用的总内存: " + r.totalMemory());
System.out.println("JVM可以使用的剩余内存: " + r.freeMemory());
System.out.println("JVM可以使用的处理器个数: " + r.availableProcessors());
System.out.println("Java的运行环境版本 " + props.getProperty("java.version"));
System.out.println("Java的运行环境供应商 " + props.getProperty("java.vendor"));
System.out.println("Java供应商的URL " + props.getProperty("java.vendor.url"));
System.out.println("Java的安装路径 " + props.getProperty("java.home"));
System.out.println("Java的虚拟机规范版本 " + props.getProperty("java.vm.specification.version"));
System.out.println("Java的虚拟机规范供应商 " + props.getProperty("java.vm.specification.vendor"));
System.out.println("Java的虚拟机规范名称 " + props.getProperty("java.vm.specification.name"));
System.out.println("Java的虚拟机实现版本 " + props.getProperty("java.vm.version"));
System.out.println("Java的虚拟机实现供应商 " + props.getProperty("java.vm.vendor"));
System.out.println("Java的虚拟机实现名称 " + props.getProperty("java.vm.name"));
System.out.println("Java运行时环境规范版本 " + props.getProperty("java.specification.version"));
System.out.println("Java运行时环境规范供应商 " + props.getProperty("java.specification.vender"));
System.out.println("Java运行时环境规范名称 " + props.getProperty("java.specification.name"));
System.out.println("Java的类格式版本号 " + props.getProperty("java.class.version"));
System.out.println("Java的类路径 " + props.getProperty("java.class.path"));
System.out.println("加载库时搜索的路径列表: " + props.getProperty("java.library.path"));
System.out.println("默认的临时文件路径: " + props.getProperty("java.io.tmpdir"));
System.out.println("一个或多个扩展目录的路径: " + props.getProperty("java.ext.dirs"));
System.out.println("操作系统的名称: " + props.getProperty("os.name"));
System.out.println("操作系统的构架: " + props.getProperty("os.arch"));
System.out.println("操作系统的版本: " + props.getProperty("os.version"));
System.out.println("文件分隔符: " + props.getProperty("file.separator"));
System.out.println("路径分隔符: " + props.getProperty("path.separator"));
System.out.println("行分隔符: " + props.getProperty("line.separator"));
System.out.println("用户的账户名称: " + props.getProperty("user.name"));
System.out.println("用户的主目录: " + props.getProperty("user.home"));
System.out.println("用户的当前工作目录: " + props.getProperty("user.dir"));
}
private static void memory() throws SigarException {
Sigar sigar = new Sigar();
Mem mem = sigar.getMem();
// 内存总量
System.out.println("内存总量: " + mem.getTotal() / 1024L + "K av");
// 当前内存使用量
System.out.println("当前内存使用量: " + mem.getUsed() / 1024L + "K used");
// 当前内存剩余量
System.out.println("当前内存剩余量: " + mem.getFree() / 1024L + "K free");
Swap swap = sigar.getSwap();
// 交换区总量
System.out.println("交换区总量: " + swap.getTotal() / 1024L + "K av");
// 当前交换区使用量
System.out.println("当前交换区使用量: " + swap.getUsed() / 1024L + "K used");
// 当前交换区剩余量
System.out.println("当前交换区剩余量: " + swap.getFree() / 1024L + "K free");
}
private static void cpu() throws SigarException {
Sigar sigar = new Sigar();
CpuInfo infos[] = sigar.getCpuInfoList();
CpuPerc cpuList[] = null;
System.out.println("cpu 总量参数情况:" + sigar.getCpu());
System.out.println("cpu 总百分比情况:" + sigar.getCpuPerc());
cpuList = sigar.getCpuPercList();
for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
CpuInfo info = infos[i];
System.out.println("第" + (i + 1) + "块CPU信息");
System.out.println("CPU的总量MHz: " + info.getMhz());// CPU的总量MHz
System.out.println("CPU生产商: " + info.getVendor());// 获得CPU的卖主Intel
System.out.println("CPU类别: " + info.getModel());// 获得CPU的类别Celeron
System.out.println("CPU缓存数量: " + info.getCacheSize());// 缓冲存储器数量
printCpuPerc(cpuList[i]);
}
}
private static void printCpuPerc(CpuPerc cpu) {
System.out.println("CPU用户使用率: " + CpuPerc.format(cpu.getUser()));// 用户使用率
System.out.println("CPU系统使用率: " + CpuPerc.format(cpu.getSys()));// 系统使用率
System.out.println("CPU当前等待率: " + CpuPerc.format(cpu.getWait()));// 当前等待率
System.out.println("CPU当前错误率: " + CpuPerc.format(cpu.getNice()));//
System.out.println("CPU当前空闲率: " + CpuPerc.format(cpu.getIdle()));// 当前空闲率
System.out.println("CPU总的使用率: " + CpuPerc.format(cpu.getCombined()));// 总的使用率
}
private static void os() {
OperatingSystem OS = OperatingSystem.getInstance();
// 操作系统内核类型如: 386、486、586等x86
System.out.println("操作系统: " + OS.getArch());
System.out.println("操作系统CpuEndian(): " + OS.getCpuEndian());//
System.out.println("操作系统DataModel(): " + OS.getDataModel());//
// 系统描述
System.out.println("操作系统的描述: " + OS.getDescription());
// 操作系统类型
// System.out.println("OS.getName(): " + OS.getName());
// System.out.println("OS.getPatchLevel(): " + OS.getPatchLevel());//
// 操作系统的卖主
System.out.println("操作系统的卖主: " + OS.getVendor());
// 卖主名称
System.out.println("操作系统的卖主名: " + OS.getVendorCodeName());
// 操作系统名称
System.out.println("操作系统名称: " + OS.getVendorName());
// 操作系统卖主类型
System.out.println("操作系统卖主类型: " + OS.getVendorVersion());
// 操作系统的版本号
System.out.println("操作系统的版本号: " + OS.getVersion());
}
private static void who() throws SigarException {
Sigar sigar = new Sigar();
Who who[] = sigar.getWhoList();
if (who != null && who.length > 0) {
for (int i = 0; i < who.length; i++) {
// System.out.println("当前系统进程表中的用户名" + String.valueOf(i));
Who _who = who[i];
System.out.println("用户控制台: " + _who.getDevice());
System.out.println("用户host: " + _who.getHost());
// System.out.println("getTime(): " + _who.getTime());
// 当前系统进程表中的用户名
System.out.println("当前系统进程表中的用户名: " + _who.getUser());
}
}
}
private static void file() throws Exception {
Sigar sigar = new Sigar();
FileSystem fslist[] = sigar.getFileSystemList();
for (int i = 0; i < fslist.length; i++) {
System.out.println("分区的盘符名称" + i);
FileSystem fs = fslist[i];
// 分区的盘符名称
System.out.println("盘符名称: " + fs.getDevName());
// 分区的盘符名称
System.out.println("盘符路径: " + fs.getDirName());
System.out.println("盘符标志: " + fs.getFlags());//
// 文件系统类型,比如 FAT32、NTFS
System.out.println("盘符类型: " + fs.getSysTypeName());
// 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
System.out.println("盘符类型名: " + fs.getTypeName());
// 文件系统类型
System.out.println("盘符文件系统类型: " + fs.getType());
FileSystemUsage usage = null;
usage = sigar.getFileSystemUsage(fs.getDirName());
switch (fs.getType()) {
case 0: // TYPE_UNKNOWN :未知
break;
case 1: // TYPE_NONE
break;
case 2: // TYPE_LOCAL_DISK : 本地硬盘
// 文件系统总大小
System.out.println(fs.getDevName() + "总大小: " + usage.getTotal() + "KB");
// 文件系统剩余大小
System.out.println(fs.getDevName() + "剩余大小: " + usage.getFree() + "KB");
// 文件系统可用大小
System.out.println(fs.getDevName() + "可用大小: " + usage.getAvail() + "KB");
// 文件系统已经使用量
System.out.println(fs.getDevName() + "已经使用量: " + usage.getUsed() + "KB");
double usePercent = usage.getUsePercent() * 100D;
// 文件系统资源的利用率
System.out.println(fs.getDevName() + "资源的利用率: " + usePercent + "%");
break;
case 3:// TYPE_NETWORK :网络
break;
case 4:// TYPE_RAM_DISK :闪存
break;
case 5:// TYPE_CDROM :光驱
break;
case 6:// TYPE_SWAP :页面交换
break;
}
System.out.println(fs.getDevName() + "读出: " + usage.getDiskReads());
System.out.println(fs.getDevName() + "写入: " + usage.getDiskWrites());
}
return;
}
private static void net() throws Exception {
Sigar sigar = new Sigar();
String ifNames[] = sigar.getNetInterfaceList();
for (int i = 0; i < ifNames.length; i++) {
String name = ifNames[i];
NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
System.out.println("网络设备名: " + name);// 网络设备名
System.out.println("IP地址: " + ifconfig.getAddress());// IP地址
System.out.println("子网掩码: " + ifconfig.getNetmask());// 子网掩码
if ((ifconfig.getFlags() & 1L) <= 0L) {
System.out.println("!IFF_UP...skipping getNetInterfaceStat");
continue;
}
NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
System.out.println(name + "接收的总包裹数:" + ifstat.getRxPackets());// 接收的总包裹数
System.out.println(name + "发送的总包裹数:" + ifstat.getTxPackets());// 发送的总包裹数
System.out.println(name + "接收到的总字节数:" + ifstat.getRxBytes());// 接收到的总字节数
System.out.println(name + "发送的总字节数:" + ifstat.getTxBytes());// 发送的总字节数
System.out.println(name + "接收到的错误包数:" + ifstat.getRxErrors());// 接收到的错误包数
System.out.println(name + "发送数据包时的错误数:" + ifstat.getTxErrors());// 发送数据包时的错误数
System.out.println(name + "接收时丢弃的包数:" + ifstat.getRxDropped());// 接收时丢弃的包数
System.out.println(name + "发送时丢弃的包数:" + ifstat.getTxDropped());// 发送时丢弃的包数
}
}
private static void ethernet() throws SigarException {
Sigar sigar = null;
sigar = new Sigar();
String[] ifaces = sigar.getNetInterfaceList();
for (int i = 0; i < ifaces.length; i++) {
NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
continue;
}
System.out.println(cfg.getName() + "IP地址:" + cfg.getAddress());// IP地址
System.out.println(cfg.getName() + "网关广播地址:" + cfg.getBroadcast());// 网关广播地址
System.out.println(cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());// 网卡MAC地址
System.out.println(cfg.getName() + "子网掩码:" + cfg.getNetmask());// 子网掩码
System.out.println(cfg.getName() + "网卡描述信息:" + cfg.getDescription());// 网卡描述信息
System.out.println(cfg.getName() + "网卡类型" + cfg.getType());//
}
}
}

View File

@ -0,0 +1,8 @@
_ _ _
| | | | (_)
___| |______ __ _ __| |_ __ ___ _ _ __
/ _ | |______/ _` |/ _` | '_ ` _ \| | '_ \
| __| | | (_| | (_| | | | | | | | | | |
\___|_| \__,_|\__,_|_| |_| |_|_|_| |_|
:: Spring Boot :: (v2.1.0.RELEASE)

View File

@ -0,0 +1,2 @@
server:
port: 8777

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>elAdmin Monitor</contextName>
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%black(%contextName-) %red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %gray(%msg%n)</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!--普通日志输出到控制台-->
<root level="info">
<appender-ref ref="console" />
</root>
</configuration>

View File

@ -0,0 +1,107 @@
package me.zhengjie.modules.monitor.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Entity
@Data
@Table(name="monitor_server")
public class Server implements Serializable {
/**
*
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
/**
*
*/
@Column(name = "name")
private String name;
/**
* IP
*/
@Column(name = "ip",nullable = false)
private String ip;
/**
* 访
*/
@Column(name = "port")
private Integer port;
/**
*
*/
@Column(name = "state")
private String state;
/**
* CPU使
*/
@Column(name = "cpu_rate")
private Double cpuRate;
/**
* CPU
*/
@Column(name = "cpu_core")
private Integer cpuCore;
/**
*
*/
@Column(name = "mem_total")
private Double memTotal;
/**
* 使
*/
@Column(name = "mem_used")
private Double memUsed;
/**
*
*/
@Column(name = "disk_total")
private Double diskTotal;
/**
* 使
*/
@Column(name = "disk_used")
private Double diskUsed;
/**
*
*/
@Column(name = "swap_total")
private Double swapTotal;
/**
* 使
*/
@Column(name = "swap_used")
private Double swapUsed;
/**
*
*/
@Column(name = "sort")
private Integer sort;
public void copy(Server source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

View File

@ -0,0 +1,12 @@
package me.zhengjie.modules.monitor.repository;
import me.zhengjie.modules.monitor.domain.Server;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author Zhang houying
* @date 2019-11-03
*/
public interface ServerRepository extends JpaRepository<Server, Integer>, JpaSpecificationExecutor<Server> {
}

View File

@ -0,0 +1,64 @@
package me.zhengjie.modules.monitor.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.monitor.domain.Server;
import me.zhengjie.modules.monitor.service.ServerService;
import me.zhengjie.modules.monitor.service.dto.ServerQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Api(tags = "Server管理")
@RestController
@RequestMapping("/api/server")
public class ServerController {
private final ServerService serverService;
public ServerController(ServerService serverService) {
this.serverService = serverService;
}
@GetMapping
@Log("查询Server")
@ApiOperation("查询Server")
@PreAuthorize("@el.check('server:list')")
public ResponseEntity getServers(ServerQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(serverService.queryAll(criteria,pageable),HttpStatus.OK);
}
@PostMapping
@Log("新增Server")
@ApiOperation("新增Server")
@PreAuthorize("@el.check('server:add')")
public ResponseEntity create(@Validated @RequestBody Server resources){
return new ResponseEntity<>(serverService.create(resources),HttpStatus.CREATED);
}
@PutMapping
@Log("修改Server")
@ApiOperation("修改Server")
@PreAuthorize("@el.check('server:edit')")
public ResponseEntity update(@Validated @RequestBody Server resources){
serverService.update(resources);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@DeleteMapping(value = "/{id}")
@Log("删除Server")
@ApiOperation("删除Server")
@PreAuthorize("@el.check('server:del')")
public ResponseEntity delete(@PathVariable Integer id){
serverService.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
}

View File

@ -0,0 +1,45 @@
package me.zhengjie.modules.monitor.service;
import me.zhengjie.modules.monitor.domain.Server;
import me.zhengjie.modules.monitor.service.dto.ServerDTO;
import me.zhengjie.modules.monitor.service.dto.ServerQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Map;
/**
* @author Zhang houying
* @date 2019-11-03
*/
public interface ServerService {
/**
*
* @param criteria
* @param pageable
* @return Map<String,Object>
*/
Map<String,Object> queryAll(ServerQueryCriteria criteria, Pageable pageable);
/**
*
* @param criteria
* @return List<ServerDTO>
*/
List<ServerDTO> queryAll(ServerQueryCriteria criteria);
/**
* ID
* @param id ID
* @return ServerDTO
*/
ServerDTO findById(Integer id);
ServerDTO create(Server resources);
void update(Server resources);
void delete(Integer id);
}

View File

@ -0,0 +1,55 @@
package me.zhengjie.modules.monitor.service.dto;
import lombok.Data;
import java.io.Serializable;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Data
public class ServerDTO implements Serializable {
// 编号
private Integer id;
// 名称
private String name;
// IP地址
private String ip;
// 访问端口
private Integer port;
// 状态
private String state;
// CPU使用率
private Float cpuRate;
// CPU内核数
private Integer cpuCore;
// 内存总数
private Float memTotal;
// 内存使用量
private Float memUsed;
// 磁盘总量
private Float diskTotal;
// 磁盘使用量
private Float diskUsed;
// 交换区总量
private Float swapTotal;
// 交换区使用量
private Float swapUsed;
// 排序
private Integer sort;
}

View File

@ -0,0 +1,20 @@
package me.zhengjie.modules.monitor.service.dto;
import lombok.Data;
import me.zhengjie.annotation.Query;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Data
public class ServerQueryCriteria{
// 模糊
@Query(type = Query.Type.INNER_LIKE)
private String name;
// 模糊
@Query(type = Query.Type.INNER_LIKE)
private String ip;
}

View File

@ -0,0 +1,99 @@
package me.zhengjie.modules.monitor.service.impl;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import me.zhengjie.modules.monitor.domain.Server;
import me.zhengjie.modules.monitor.repository.ServerRepository;
import me.zhengjie.modules.monitor.service.ServerService;
import me.zhengjie.modules.monitor.service.dto.ServerDTO;
import me.zhengjie.modules.monitor.service.dto.ServerQueryCriteria;
import me.zhengjie.modules.monitor.service.mapper.ServerMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ServerServiceImpl implements ServerService {
private final ServerRepository serverRepository;
private final ServerMapper serverMapper;
public ServerServiceImpl(ServerRepository serverRepository, ServerMapper serverMapper) {
this.serverRepository = serverRepository;
this.serverMapper = serverMapper;
}
@Override
public Map<String,Object> queryAll(ServerQueryCriteria criteria, Pageable pageable){
Page<Server> page = serverRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
page.forEach(server -> {
try {
server.setState("1");
String url = String.format("http://%s:%d/api/serverMonitor",server.getIp(),server.getPort());
String res = HttpUtil.get(url,1000);
JSONObject obj = JSONObject.parseObject(res);
server.setCpuRate(obj.getDouble("cpuRate"));
server.setCpuCore(obj.getInteger("cpuCore"));
server.setMemTotal(obj.getDouble("memTotal"));
server.setMemUsed(obj.getDouble("memUsed"));
server.setDiskTotal(obj.getDouble("diskTotal"));
server.setDiskUsed(obj.getDouble("diskUsed"));
server.setSwapTotal(obj.getDouble("swapTotal"));
server.setSwapUsed(obj.getDouble("swapUsed"));
} catch (Exception e) {
server.setState("0");
e.printStackTrace();
}
});
return PageUtil.toPage(page.map(serverMapper::toDto));
}
@Override
public List<ServerDTO> queryAll(ServerQueryCriteria criteria){
return serverMapper.toDto(serverRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
public ServerDTO findById(Integer id) {
Server server = serverRepository.findById(id).orElseGet(Server::new);
ValidationUtil.isNull(server.getId(),"Server","id",id);
return serverMapper.toDto(server);
}
@Override
@Transactional(rollbackFor = Exception.class)
public ServerDTO create(Server resources) {
return serverMapper.toDto(serverRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Server resources) {
Server server = serverRepository.findById(resources.getId()).orElseGet(Server::new);
ValidationUtil.isNull( server.getId(),"Server","id",resources.getId());
server.copy(resources);
serverRepository.save(server);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Integer id) {
serverRepository.deleteById(id);
}
}

View File

@ -0,0 +1,16 @@
package me.zhengjie.modules.monitor.service.mapper;
import me.zhengjie.base.BaseMapper;
import me.zhengjie.modules.monitor.domain.Server;
import me.zhengjie.modules.monitor.service.dto.ServerDTO;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @author Zhang houying
* @date 2019-11-03
*/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ServerMapper extends BaseMapper<ServerDTO, Server> {
}

View File

@ -15,7 +15,8 @@
<module>eladmin-system</module>
<module>eladmin-tools</module>
<module>eladmin-generator</module>
</modules>
<module>eladmin-monitor</module>
</modules>
<name>EL-ADMIN后台管理系统</name>
<url>http://auauz.net</url>