java获取服务器信息

  • Post author:
  • Post category:java



java获取服务器信息需要用到sigar.jar,但该jar在linux下依赖于libsigar-amd64-linux.so、

libsigar-x86-linux.so。在window下依赖于sigar-amd64-winnt.dll、

sigar-x86-winnt.dll。配置文件这存在这模拟系统命名的操作,可以通过这些系统命名来获取系统的参数。









默认情况下是将依赖文件放在jdk下的lib包中,这样项目启动的时候会自动加载这些配置文件。但每个人使用就需要这么配置,太麻烦了,为了方便我们写一个公共类来优化这一问题。


package com.dhcc.isccore.common.util;

import java.io.File;

import org.hyperic.sigar.Sigar;

import com.dhcc.isccore.common.constant.IsccoreConstant;

public class SigarUtils {
	public final static Sigar sigar = initSigar();

	public static Sigar initSigar() {
		try {
			File classPath = new File(IsccoreConstant.SIGAR_PATH);

			String path = System.getProperty("java.library.path");
			String sigarLibPath = classPath.getCanonicalPath();
			// 为防止java.library.path重复加,此处判断了一下
			if (!path.contains(sigarLibPath)) {
				if (isOSWin()) {
					path += ";" + sigarLibPath;
				} else {
					path += ":" + sigarLibPath;
				}
				System.setProperty("java.library.path", path);
			}
			return new Sigar();
		} catch (Exception e) {
			return null;
		}
	}

	public static boolean isOSWin() {// OS 版本判断
		String OS = System.getProperty("os.name").toLowerCase();
		if (OS.indexOf("win") >= 0) {
			return true;
		} else
			return false;
	}
}

文件存放位置如下:



jar依赖:


<dependency>
	<groupId>org.hyperic</groupId>
	<artifactId>sigar</artifactId>
	<version>1.6.5.132</version>
</dependency>



获取服务器信息的vo类定义:


package com.dhcc.isccore.entity.serverinfo;

import java.util.Date;
import java.util.List;

import org.hyperic.sigar.NetInterfaceConfig;

public class ServerInfoVo {

	private String serverIP;		//服务器IP
	private String serverURL;		//服务器Url
	private String serverType;		//服务器类型
	private Date serverTime;		//服务器时间
	
	private String osName;			//操作系统名称
	private String osVersion;		//操作系统版本
	private String userName;		//用户名称
	private String userHome;		//用户主目录
	private String osTimeZone;		//操作系统时区
	
	private String memTotal;		//物理内存总量
	private String memUsed;			//已使用的物理内存
	private String memFree;			//物理内存剩余量
	
	private int cpuNum;				//cpu总数
	private List<CpuInfoVo> cpuList;//cpu信息
	
	private int netNum;			//网卡总数
	private List<NetInterfaceConfig> netList;	//网卡信息
	
	private String javaPath;		//java安路径
	private String javaVendor;		//java运行时供应商
	private String javaVersion;		//java版本
	private String javaName;		//java运行时名称
	private String jvmVersion;		//java虚拟机版本
	private String jvmTotalMemory;	//java虚拟机总内存
	private String jvmFreeMemory;	//java虚拟机剩余内存
	
	private String databaseType;	//数据库类型
	private String databaseVersion;	//数据库类型
	private String databaseDriver;	//数据库驱动
	private String driverVersion;	//数据库驱动版本
	private String jdbcUrl;			//数据库连接url
	
	public String getServerIP() {
		return serverIP;
	}
	public void setServerIP(String serverIP) {
		this.serverIP = serverIP;
	}
	public String getServerURL() {
		return serverURL;
	}
	public void setServerURL(String serverURL) {
		this.serverURL = serverURL;
	}
	public String getServerType() {
		return serverType;
	}
	public void setServerType(String serverType) {
		this.serverType = serverType;
	}
	public String getOsName() {
		return osName;
	}
	public void setOsName(String osName) {
		this.osName = osName;
	}
	public String getOsVersion() {
		return osVersion;
	}
	public void setOsVersion(String osVersion) {
		this.osVersion = osVersion;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserHome() {
		return userHome;
	}
	public void setUserHome(String userHome) {
		this.userHome = userHome;
	}
	public String getOsTimeZone() {
		return osTimeZone;
	}
	public void setOsTimeZone(String osTimeZone) {
		this.osTimeZone = osTimeZone;
	}
	public String getJavaVendor() {
		return javaVendor;
	}
	public void setJavaVendor(String javaVendor) {
		this.javaVendor = javaVendor;
	}
	public String getJavaVersion() {
		return javaVersion;
	}
	public void setJavaVersion(String javaVersion) {
		this.javaVersion = javaVersion;
	}
	public String getJavaName() {
		return javaName;
	}
	public void setJavaName(String javaName) {
		this.javaName = javaName;
	}
	public String getJvmVersion() {
		return jvmVersion;
	}
	public void setJvmVersion(String jvmVersion) {
		this.jvmVersion = jvmVersion;
	}
	public String getJvmTotalMemory() {
		return jvmTotalMemory;
	}
	public void setJvmTotalMemory(String jvmTotalMemory) {
		this.jvmTotalMemory = jvmTotalMemory;
	}
	public String getJvmFreeMemory() {
		return jvmFreeMemory;
	}
	public void setJvmFreeMemory(String jvmFreeMemory) {
		this.jvmFreeMemory = jvmFreeMemory;
	}
	public String getDatabaseType() {
		return databaseType;
	}
	public void setDatabaseType(String databaseType) {
		this.databaseType = databaseType;
	}
	public String getDatabaseVersion() {
		return databaseVersion;
	}
	public void setDatabaseVersion(String databaseVersion) {
		this.databaseVersion = databaseVersion;
	}
	public String getDatabaseDriver() {
		return databaseDriver;
	}
	public void setDatabaseDriver(String databaseDriver) {
		this.databaseDriver = databaseDriver;
	}
	public String getDriverVersion() {
		return driverVersion;
	}
	public void setDriverVersion(String driverVersion) {
		this.driverVersion = driverVersion;
	}
	public String getJdbcUrl() {
		return jdbcUrl;
	}
	public void setJdbcUrl(String jdbcUrl) {
		this.jdbcUrl = jdbcUrl;
	}
	
	public Date getServerTime() {
		return serverTime;
	}
	public void setServerTime(Date serverTime) {
		this.serverTime = serverTime;
	}
	public String getJavaPath() {
		return javaPath;
	}
	public void setJavaPath(String javaPath) {
		this.javaPath = javaPath;
	}
	public int getCpuNum() {
		return cpuNum;
	}
	public void setCpuNum(int cpuNum) {
		this.cpuNum = cpuNum;
	}
	public List<CpuInfoVo> getCpuList() {
		return cpuList;
	}
	public void setCpuList(List<CpuInfoVo> cpuList) {
		this.cpuList = cpuList;
	}
	public int getNetNum() {
		return netNum;
	}
	public void setNetNum(int netNum) {
		this.netNum = netNum;
	}
	public List<NetInterfaceConfig> getNetList() {
		return netList;
	}
	public void setNetList(List<NetInterfaceConfig> netList) {
		this.netList = netList;
	}
	public String getMemTotal() {
		return memTotal;
	}
	public void setMemTotal(String memTotal) {
		this.memTotal = memTotal;
	}
	public String getMemUsed() {
		return memUsed;
	}
	public void setMemUsed(String memUsed) {
		this.memUsed = memUsed;
	}
	public String getMemFree() {
		return memFree;
	}
	public void setMemFree(String memFree) {
		this.memFree = memFree;
	}
	
}

获取服务器信息的实现类:


public void findServerInfo(BaseAbstractDto baseAbstractDto){
	try {
		SigarUtils.initSigar();			//初始化动态库链接路径
		ServerInfoDto dto = super.getExactlyDto(baseAbstractDto);
		Properties props=System.getProperties();
		HttpServletRequest request = ServletActionContext.getRequest();
		Runtime runTime = Runtime.getRuntime();
		InetAddress address = InetAddress.getLocalHost();
			
		//服务信息
		ServerInfoVo serverInfoVo = new  ServerInfoVo();
		InetAddress.getLocalHost().getHostAddress();
		serverInfoVo.setServerIP(address.getHostAddress());
		serverInfoVo.setServerURL(
				request.getScheme()					//请求头
				+"://" + address.getHostAddress() 	//服务器地址  
				+ ":"   
				+ request.getServerPort()        	//端口号  
				+ request.getContextPath());      	//项目名称 
		ServletContext application = request.getSession().getServletContext();
		serverInfoVo.setServerType(application.getServerInfo());
		serverInfoVo.setServerTime(new Date());
			
		//操作系统
		serverInfoVo.setOsName(props.getProperty("os.name")+"  "+props.getProperty("os.arch"));
		serverInfoVo.setOsVersion(props.getProperty("os.version"));
		serverInfoVo.setUserName(props.getProperty("user.name"));
		serverInfoVo.setUserHome(props.getProperty("user.home"));
		Calendar cal = Calendar.getInstance();
		TimeZone timeZone = cal.getTimeZone();
		serverInfoVo.setOsTimeZone(timeZone.getDisplayName());
			
		//Cpu
		Sigar sigar = new Sigar();
	        CpuInfo cpuInfos[] = sigar.getCpuInfoList();
	        serverInfoVo.setCpuNum(cpuInfos.length);
	        CpuPerc cpuList[] = sigar.getCpuPercList();
	        List<CpuInfoVo> cpuVoList = new ArrayList<CpuInfoVo>();
	        for(int m=0;m<cpuList.length;m++){
	        	CpuInfoVo cpuInfoVo = new CpuInfoVo();
	        	cpuInfoVo.setCpuMhz(cpuInfos[m].getMhz());
	        	String cpuIdle = String.format("%.2f",cpuList[m].getIdle()*100)+"%";
	        	cpuInfoVo.setCpuLdle(cpuIdle);
	        	String cpuCombined = String.format("%.2f",cpuList[m].getCombined()*100)+"%";
	        	cpuInfoVo.setCpuCombined(cpuCombined);
	        	cpuVoList.add(cpuInfoVo);
	        }
	        serverInfoVo.setCpuList(cpuVoList);
	        
	        //网卡信息
	        String netInfos[] = sigar.getNetInterfaceList();
	        List<NetInterfaceConfig> netList = new ArrayList<NetInterfaceConfig>();
	        for(int i=0;i<netInfos.length;i++){
	        	NetInterfaceConfig netInfo = sigar.getNetInterfaceConfig(netInfos[i]); 
	        	if((NetFlags.LOOPBACK_ADDRESS.equals(netInfo.getAddress()))  	//127.0.0.1 
                        || (netInfo.getFlags() == 0)  							//标识为0
                        || (NetFlags.NULL_HWADDR.equals(netInfo.getHwaddr()))	//MAC地址不存在
                        || (NetFlags.ANY_ADDR.equals(netInfo.getAddress()))		//0.0.0.0
	        			){
	        		continue;
	        	}
	        	netList.add(netInfo);
	        }
	        serverInfoVo.setNetNum(netList.size());
	        serverInfoVo.setNetList(netList);
	        
	        //物理内存
	        Mem mem = sigar.getMem();  
	        serverInfoVo.setMemTotal((mem.getTotal()/(1024*1024))+"M");
	        serverInfoVo.setMemUsed((mem.getUsed()/(1024*1024))+"M");
	        serverInfoVo.setMemFree((mem.getFree()/(1024*1024))+"M");
	        
		//java配置
		serverInfoVo.setJavaPath(props.getProperty("java.home"));
		serverInfoVo.setJavaVendor(props.getProperty("java.vendor"));
		serverInfoVo.setJavaVersion(props.getProperty("java.version"));
		serverInfoVo.setJavaName(props.getProperty("java.specification.name"));
		serverInfoVo.setJvmVersion(props.getProperty("java.vm.version"));
		serverInfoVo.setJvmTotalMemory((int)(runTime.totalMemory()/(1024*1024))+"M");
		serverInfoVo.setJvmFreeMemory((int)(runTime.freeMemory()/(1024*1024))+"M");
			
			//数据库信息
		findDatabase(serverInfoVo);
		dto.setServerInfoVo(serverInfoVo);
			
	} catch (Exception e) {
		e.printStackTrace();
	}
}

//数据库连接信息
public void findDatabase(ServerInfoVo serverInfoVo){
	try{
		PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("hibernate.properties");//读取配置文件的连接信息
		String driver = propertiesUtil.getProperty("jdbc.driver");
		String jdbcUrl = propertiesUtil.getProperty("jdbc.url");
		serverInfoVo.setJdbcUrl(jdbcUrl);
		String username = propertiesUtil.getProperty("jdbc.username");
		String password = propertiesUtil.getProperty("jdbc.password");
		Class.forName(driver);
		Connection con = (Connection) DriverManager.getConnection(jdbcUrl,username,password);
		DatabaseMetaData metaData = (DatabaseMetaData) con.getMetaData();
		serverInfoVo.setDatabaseType(metaData.getDatabaseProductName());
		serverInfoVo.setDatabaseVersion(metaData.getDatabaseProductVersion());
		serverInfoVo.setDatabaseDriver(metaData.getDriverName());
		serverInfoVo.setDriverVersion(metaData.getDriverVersion());
	}catch(Exception e){
		e.printStackTrace();
	}
}

显示效果如下:








上诉方案主要讲解服务器信息的实现方法,不要全抄代码,部分无关紧要的代码并未上传,仅供参考,谢谢!










版权声明:本文为mafan121原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。