Ver código fonte

Merge branch 'master' of http://192.168.1.220:10080/esb/esb

zhenglingfeng 8 anos atrás
pai
commit
0ba1a5222a

+ 1 - 1
hos-rest/src/main/java/com/yihu/hos/rest/common/filter/HibernateFilter.java

@ -1,6 +1,6 @@
package com.yihu.hos.rest.common.filter;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import javax.servlet.annotation.WebFilter;

+ 3 - 3
hos-rest/src/main/resources/spring/applicationContext.xml

@ -37,7 +37,7 @@
    </bean>
    <!--Hibernate 会话管理器配置-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
@ -61,7 +61,7 @@
    </bean>
    <!-- 将多个配置文件读取到容器中,交给Spring管理 -->
    <!--Hibernate 事务配置-->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
@ -80,7 +80,7 @@
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--Hibernate模版配置 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" scope="singleton">-->

+ 3 - 3
hos-web-framework-dependencies/pom.xml

@ -12,13 +12,13 @@
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
        <relativePath/> <!-- lookup parent from repository1212 -->
    </parent>
    <properties>
        <camel.version>2.17.1</camel.version>
        <spring.version>4.3.2.RELEASE</spring.version>
        <hibernate.version>5.2.3.Final</hibernate.version>
        <!--<spring.version>4.2.8.RELEASE</spring.version>-->
        <hibernate.version>4.3.11.Final</hibernate.version>
        <camel.osgi.export.pkg>org.apache.camel.dataformat.xmljson.*</camel.osgi.export.pkg>
        <camel.osgi.export.service>org.apache.camel.spi.DataFormatResolver;dataformat=xmljson</camel.osgi.export.service>
        <!--<spring.security.version>4.0.2.RELEASE</spring.security.version>-->

+ 1 - 1
hos-web-framework/src/main/java/com/yihu/hos/web/framework/dao/SQLGeneralDAO.java

@ -21,7 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import javax.annotation.Resource;
import java.io.IOException;

+ 30 - 1
pom.xml

@ -64,7 +64,6 @@
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--=============tilesJSP布局框架 start =============-->
@ -89,6 +88,36 @@
        <!--========== hibernate start=======-->
        <!--========== hibernate end=========-->
        <dependency>
            <groupId>org.apache.xmlgraphics</groupId>
            <artifactId>fop</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>xalan</groupId>
            <artifactId>xalan</artifactId>
            <version>2.7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>jurt</artifactId>
            <version>2.3.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>juh</artifactId>
            <version>2.3.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.fusesource</groupId>
            <artifactId>sigar</artifactId>
            <version>1.6.4</version>
        </dependency>
    </dependencies>

+ 10 - 1
src/main/java/com/yihu/hos/ESBApplication.java

@ -5,14 +5,23 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.jms.Queue;
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableJms
public class ESBApplication {
@EnableScheduling
public class ESBApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ESBApplication.class);
    }
    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(ESBApplication.class);

+ 1 - 2
src/main/java/com/yihu/hos/common/ActiveMqUtil.java

@ -3,7 +3,6 @@ package com.yihu.hos.common;
import com.yihu.hos.common.activeMq.ActiveMqConstants;
import com.yihu.hos.common.activeMq.ActivemqConfiguration;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.stereotype.Component;
import javax.jms.*;
import java.util.Map;
@ -14,7 +13,7 @@ import java.util.concurrent.ConcurrentHashMap;
 * @vsrsion 1.0
 * Created at 2016/8/22.
 */
@Component
//@Component
public class ActiveMqUtil {
    static ConnectionFactory connectionFactory;

+ 75 - 0
src/main/java/com/yihu/hos/common/MongodbUtil.java

@ -0,0 +1,75 @@
package com.yihu.hos.common;
import com.mongodb.client.MongoDatabase;
import com.yihu.ehr.dbhelper.mongodb.MongodbFactory;
import com.yihu.ehr.dbhelper.mongodb.MongodbHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/13.
 */
public class MongodbUtil extends MongodbHelper {
    private MongoDatabase db;
    public String errorMessage;
    public MongodbUtil() {
        this.db = MongodbFactory.getDB();
    }
    public MongodbUtil(String dbName) {
        this.db = MongodbFactory.getDB(dbName);
    }
    public synchronized boolean insert(String name, JSONObject data) {
        try {
            this.db.getCollection(name).insertOne(Document.parse(data.toString()));
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            this.errorMessage = var4.getMessage();
            return false;
        }
    }
    public synchronized boolean insertArray(String name, List<JSONObject> data) {
        try {
            this.db.getCollection(name).insertOne(Document.parse(data.toString()));
            return true;
        } catch (Exception var4) {
            var4.printStackTrace();
            this.errorMessage = var4.getMessage();
            return false;
        }
    }
    public synchronized boolean insertList(String name,JSONArray dataList) {
        try {
            ArrayList e = new ArrayList();
            Iterator var4 = dataList.iterator();
            while(var4.hasNext()) {
                JSONObject json = (JSONObject)var4.next();
                Document doc = Document.parse(json.toString());
                e.add(doc);
            }
            this.db.getCollection(name).insertMany(e);
            return true;
        } catch (Exception var7) {
            var7.printStackTrace();
            this.errorMessage = var7.getMessage();
            return false;
        }
    }
}

+ 525 - 0
src/main/java/com/yihu/hos/common/SigarDemoUtils.java

@ -0,0 +1,525 @@
package com.yihu.hos.common;
import com.yihu.hos.core.datatype.NumberUtil;
import org.hyperic.sigar.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/10.
 */
public class SigarDemoUtils {
    public final static Sigar sigar = initSigar();
    private static Sigar initSigar() {
        try {
            //此处只为得到依赖库文件的目录,可根据实际项目自定义
            URL claaPath = SigarDemoUtils.class.getResource("/");
            String path = System.getProperty("java.library.path");
            String sigarLibPath = claaPath.getPath();
            //为防止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) {
            e.printStackTrace();
            return null;
        }
    }
    public URL getUrl(){
        return this.getClass().getResource("/");
    }
    public static Map<String,Object> getEnvInfo(){
        Map<String,Object> result = new HashMap<>();
        try {
        //cpu
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuList[] = null;
        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());// 缓冲存储器数量
            CpuPerc cpu = cpuList[i];
            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()));// 总的使用率
        }
        //以太网
            String ifNames[] = sigar.getNetInterfaceList();
            for (int i = 0; i < ifNames.length; i++) {
                String name = ifNames[i];
                NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(name);
                if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                        || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
                    continue;
                }
                System.out.println("网络设备名:    " + name);// 网络设备名
                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());//
                if ((cfg.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());// 发送时丢弃的包数
                System.out.println(name + "发送时:" + ifstat.getRxOverruns());// 发送时丢弃的包数
//            System.out.println(name + "接收时:" + ifstat.get());// 发送时丢弃的包数
            }
        //内存
        Mem mem = sigar.getMem();
        // 内存总量
        System.out.println("内存总量:    " + mem.getTotal() / 1024L + "K av");
        // 当前内存使用量
        System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L / 1024L + "M used");
        // 当前内存剩余量
        System.out.println("当前内存剩余量:    " + mem.getFree() / 1024L / 1024L + "M free");
        Swap swap = sigar.getSwap();
        // 交换区总量
        System.out.println("交换区总量:    " + swap.getTotal() / 1024L / 1024L + "M av");
        // 当前交换区使用量
        System.out.println("当前交换区使用量:    " + swap.getUsed() / 1024L / 1024L + "M used");
        // 当前交换区剩余量
        System.out.println("当前交换区剩余量:    " + swap.getFree() / 1024L / 1024L + "M free");
        //硬盘
            file();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
//    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();
//        }
//    }
    /**
     * 是否是windows系统
     * @return
     */
    public static boolean isOSWin(){//OS 版本判断
        String OS = System.getProperty("os.name").toLowerCase();
        if (OS.indexOf("win") >= 0) {
            return true;
        } else return false;
    }
    /* ==================================================   以下是打印测试   ========================================================================== */
    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"));
    }
    /**
     * 内存信息
     * @return
     * @throws SigarException
     */
    public static Map<String,Object> memory() throws SigarException {
        Mem mem = sigar.getMem();
        Swap swap = sigar.getSwap();
        Map<String,Object> memory = new HashMap<>();
        memory.put("total",mem.getTotal() / 1024L/ 1024L/ 1024L);
        memory.put("used",mem.getUsed() / 1024L / 1024L/ 1024L);
        memory.put("free",mem.getFree() / 1024L / 1024L/ 1024L);
        memory.put("freePerc",mem.getFreePercent());
        memory.put("usedPerc",mem.getUsedPercent());
        memory.put("swapTotal",swap.getTotal() / 1024L / 1024L / 1024L);
        memory.put("swapUsed",swap.getUsed() / 1024L / 1024L / 1024L);
        memory.put("swapFree",swap.getFree() / 1024L / 1024L / 1024L);
        // 内存总量
        System.out.println("内存总量:    " + mem.getTotal() / 1024L / 1024L + "M av");
        // 当前内存使用量
        System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L / 1024L + "M used");
        // 当前内存剩余量
        System.out.println("当前内存剩余量:    " + mem.getFree() / 1024L / 1024L + "M free");
        // 交换区总量
        System.out.println("交换区总量:    " + swap.getTotal() / 1024L / 1024L + "M av");
        // 当前交换区使用量
        System.out.println("当前交换区使用量:    " + swap.getUsed() / 1024L / 1024L + "M used");
        // 当前交换区剩余量
        System.out.println("当前交换区剩余量:    " + swap.getFree() / 1024L / 1024L + "M free");
        return memory;
    }
    /**
     * cpu使用情况
     * @return
     * @throws SigarException
     */
    public static Map<String,Object> cpu() throws SigarException {
        Map<String,Object> cpuMap = new HashMap<>();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuPerc =  sigar.getCpuPerc();
        CpuInfo info1 = infos[0];
        cpuMap.put("quantity",infos.length);
        cpuMap.put("model",info1.getModel());
        cpuMap.put("totalCores",info1.getTotalCores());
        cpuMap.put("totalSockets",info1.getTotalSockets());
        cpuMap.put("Mhz",info1.getMhz());
        cpuMap.put("totalPerc",NumberUtil.formatNumber(cpuPerc.getCombined() *100,"#.00"));
        cpuMap.put("userPerc",NumberUtil.formatNumber(cpuPerc.getUser() *100,"##.00"));
        cpuMap.put("sysPerc",NumberUtil.formatNumber(cpuPerc.getSys() *100,"##.00"));
        cpuMap.put("wait",NumberUtil.formatNumber(cpuPerc.getWait() *100,"##.00"));
        cpuMap.put("nice",NumberUtil.formatNumber(cpuPerc.getNice() *100,"##.00"));
        cpuMap.put("freePerc",NumberUtil.formatNumber(cpuPerc.getIdle() *100,"##.00"));
        System.out.println("CpuInfo mhz:" + info1.getMhz()/1024);
        System.out.println("CpuInfo vendor:" + info1.getVendor());
        System.out.println("CpuInfo Model:" + info1.getModel());
        System.out.println("CpuInfo cacheSize:" + info1.getCacheSize());
        System.out.println("CpuInfo totalCores:" + info1.getTotalCores());
        System.out.println("CpuInfo totalSockets:" + info1.getTotalSockets());
        System.out.println("CpuInfo coresPerSocket:" + info1.getCoresPerSocket());
        System.out.println("=========: CPU的总使用率=====================");
        System.out.println("=========: 系统使用率:"+CpuPerc.format(cpuPerc.getSys()));
        System.out.println("=========: CPU当前错误率:"+CpuPerc.format(cpuPerc.getNice()));
        System.out.println("=========: CPU当前等待率:"+CpuPerc.format(cpuPerc.getWait()));
        System.out.println("=========: CPU当前空闲率:" + CpuPerc.format(cpuPerc.getIdle()));
        System.out.println("=========: CPU插槽数:" + cpuPerc.getStolen());
        return cpuMap;
    }
    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 {
        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());
            }
        }
    }
    /**
     * 硬盘信息
     */
    public static List<Map<String,Object>> file()  {
        List<Map<String,Object>> files = new ArrayList<>();
        Map<String,Object> fileMap = null;
        FileSystem fslist[] = new FileSystem[0];
        try {
            fslist = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            FileSystem fs = fslist[i];
            fileMap = new HashMap<>();
            System.out.println("分区的盘符名称" + 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());
            switch (fs.getType()) {
                case 0: // TYPE_UNKNOWN :未知
                    break;
                case 1: // TYPE_NONE
                    break;
                case 2: // TYPE_LOCAL_DISK : 本地硬盘
                    FileSystemUsage usage  = sigar.getFileSystemUsage(fs.getDirName());
                    fileMap.put("devName",fs.getDevName());
                    fileMap.put("dirName",fs.getDirName());
                    fileMap.put("flags",fs.getFlags());
                    fileMap.put("sysTypeName",fs.getSysTypeName());
                    fileMap.put("typeName",fs.getTypeName());
                    fileMap.put("type",fs.getType());
                    fileMap.put("total",usage.getTotal()  / 1024L / 1024L);
                    fileMap.put("free",usage.getFree() / 1024L / 1024L );
                    fileMap.put("aVall",usage.getAvail() / 1024L / 1024L );//可用大小
                    fileMap.put("used",usage.getUsed() / 1024L / 1024L );
                    fileMap.put("usePercent", usage.getUsePercent() * 100D );
                    fileMap.put("diskRead", usage.getDiskReads() );
                    fileMap.put("diskWrite", usage.getDiskWrites() );
                    files.add(fileMap);
                    System.out.println(fs.getDevName() + "读出:    " + usage.getDiskReads());
                    System.out.println(fs.getDevName() + "写入:    " + usage.getDiskWrites());
                    // 文件系统总大小
                    System.out.println(fs.getDevName() + "总大小:    " + usage.getTotal()  / 1024L + "MB");
                    // 文件系统剩余大小
                    System.out.println(fs.getDevName() + "剩余大小:    " + usage.getFree() / 1024L + "MB");
                    // 文件系统可用大小
                    System.out.println(fs.getDevName() + "可用大小:    " + usage.getAvail() / 1024L + "MB");
                    // 文件系统已经使用量
                    System.out.println(fs.getDevName() + "已经使用量:    " + usage.getUsed() / 1024L + "MB");
                    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;
            }
        }
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return files;
    }
    /**
     * 网络信息
     * @throws Exception
     */
    public static Map<String,Object> net() throws Exception {
        List<Map<String,Object>> netList = new ArrayList<>();
        Map<String,Object> netMap = new HashMap<>();
        NetInterfaceConfig netConfig = sigar.getNetInterfaceConfig();
        NetInterfaceStat netIfStat = sigar.getNetInterfaceStat(netConfig.getName());
        Map<String,Object> bps = populate(netConfig.getName());
        netMap.put("address",netConfig.getAddress());
        netMap.put("broadcast",netConfig.getBroadcast());
        netMap.put("netmask",netConfig.getNetmask());
        netMap.put("rxPackets",netIfStat.getRxPackets());
        netMap.put("txPackets",netIfStat.getTxPackets());
        netMap.put("rxBytes",netIfStat.getRxBytes());
        netMap.put("txBytes",netIfStat.getTxBytes());
        netMap.put("txPackets",netIfStat.getTxPackets());
        netMap.put("txbps",bps.get("txbps"));
        netMap.put("rxbps",bps.get("rxbps"));
//        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());// 发送时丢弃的包数
//
//            System.out.println(name + "发送时:" + ifstat.getRxOverruns());// 发送时丢弃的包数
////            System.out.println(name + "接收时:" + ifstat.get());// 发送时丢弃的包数
//
//        }
        return netMap;
    }
    private static void ethernet() throws SigarException {
        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());//
     }
    }
    /**
     * 網絡傳輸速率
     * @param name
     * @throws SigarException
     */
    public static Map<String,Object> populate(String name)
            throws SigarException {
        Map<String,Object> bps = new HashMap<>();
        try {
            long start = System.currentTimeMillis();
            NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
            long rxBytesStart = statStart.getRxBytes();
            long txBytesStart = statStart.getTxBytes();
            Thread.sleep(1000);
            long end = System.currentTimeMillis();
            NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
            long rxBytesEnd = statEnd.getRxBytes();
            long txBytesEnd = statEnd.getTxBytes();
            long rxbps = ((rxBytesEnd - rxBytesStart)*8/1024) / ((end-start)/1000);
            long txbps = ((txBytesEnd - txBytesStart)*8/1024) / ((end-start)/1000);
            bps.put("rxbps",rxbps);
            bps.put("txbps",txbps);
            System.out.println("#######rxbps: "+rxbps +" txbps: "+txbps);
        } catch (SigarException e) {
        } catch (Exception e) {
        }
        return bps;
    }
}

+ 361 - 0
src/main/java/com/yihu/hos/common/SigarUtil.java

@ -0,0 +1,361 @@
package com.yihu.hos.common;
import org.hyperic.sigar.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
/**
 * sigar 服务器硬件指标 工具类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/10.
 */
public class SigarUtil {
    public final static Sigar sigar = initSigar();
    private static Sigar initSigar() {
        try {
            //此处只为得到依赖库文件的目录,可根据实际项目自定义
            URL claaPath = SigarUtil.class.getResource("/");
            String path = System.getProperty("java.library.path");
            String sigarLibPath = claaPath.getPath();
            //为防止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) {
            e.printStackTrace();
            return null;
        }
    }
    public URL getUrl() {
        return this.getClass().getResource("/");
    }
//    public static void main(String[] args) {
//        DecimalFormat df = new DecimalFormat("#0.00");
//        double d = 0;
//        String f = df.format(d);
//        double e = Double.parseDouble(String.format("%.2f", d));
//        System.out.println(e);
//    }
    /**
     * 是否是windows系统
     *
     * @return
     */
    public static boolean isOSWin() {//OS 版本判断
        String OS = System.getProperty("os.name").toLowerCase();
        if (OS.indexOf("win") >= 0) {
            return true;
        } else return false;
    }
    /* ==================================================   以下是打印测试   ========================================================================== */
    /**
     * 系统信息  jvm等
     *
     * @throws UnknownHostException
     */
    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"));
    }
    /**
     * 内存信息
     *
     * @return 返回单位 :G
     * @throws SigarException
     */
    public static Map<String, Object> memory() throws SigarException {
        Mem mem = sigar.getMem();
        Swap swap = sigar.getSwap();
        Map<String, Object> memory = new HashMap<>();
        memory.put("total", getDouble((double)mem.getTotal() / 1024L / 1024L / 1024L));
        memory.put("used",  getDouble((double)mem.getUsed() / 1024L / 1024L / 1024L));
        memory.put("free",  getDouble((double)mem.getFree() / 1024L / 1024L / 1024L));
        memory.put("freePerc", getDouble(mem.getFreePercent() / 1024L / 1024L / 1024L));
        memory.put("usedPerc", getDouble(mem.getUsedPercent() / 1024L / 1024L / 1024L));
        //交换区
        memory.put("swapTotal", getDouble((double)swap.getTotal() / 1024L / 1024L / 1024L));
        memory.put("swapUsed",  getDouble((double)swap.getUsed() / 1024L / 1024L / 1024L));
        memory.put("swapFree", getDouble((double) swap.getFree() / 1024L / 1024L / 1024L));
        return memory;
    }
    /**
     * cpu使用情况
     *
     * @return
     * @throws SigarException
     */
    public static Map<String, Object> cpu() throws SigarException {
        Map<String, Object> cpuMap = new HashMap<>();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuPerc = sigar.getCpuPerc();
        CpuInfo info1 = infos[0];
        //cpu信息
        cpuMap.put("quantity", infos.length);
        cpuMap.put("model", info1.getModel());
        cpuMap.put("totalCores", info1.getTotalCores());
        cpuMap.put("totalSockets", info1.getTotalSockets());
        cpuMap.put("Mhz", info1.getMhz());
        //cpu使用率
        String totalPerc = String.format("%.2f", cpuPerc.getCombined() * 100);
        String userPerc = String.format("%.2f", cpuPerc.getUser() * 100);
        String sysPerc = String.format("%.2f", cpuPerc.getSys() * 100);
        String wait = String.format("%.2f", cpuPerc.getWait() * 100);
        String nice = String.format("%.2f", cpuPerc.getNice() * 100);
        String freePerc = String.format("%.2f", cpuPerc.getIdle() * 100);
        cpuMap.put("totalPerc", getDouble(cpuPerc.getCombined() * 100));
        cpuMap.put("userPerc", getDouble(cpuPerc.getUser() * 100));
        cpuMap.put("sysPerc", getDouble(cpuPerc.getSys() * 100));
        cpuMap.put("wait", getDouble(cpuPerc.getWait() * 100));
        cpuMap.put("nice", getDouble(cpuPerc.getNice() * 100));
        cpuMap.put("freePerc", getDouble(cpuPerc.getIdle() * 100));
        return cpuMap;
    }
    /**
     * 操作系统信息
     */
    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 {
        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());
            }
        }
    }
    /**
     * 硬盘信息
     */
    public static List<Map<String, Object>> file() {
        List<Map<String, Object>> files = new ArrayList<>();
        Map<String, Object> fileMap = null;
        FileSystem fslist[] = new FileSystem[0];
        try {
            fslist = sigar.getFileSystemList();
            for (int i = 0; i < fslist.length; i++) {
                FileSystem fs = fslist[i];
                fileMap = new HashMap<>();
                switch (fs.getType()) {
                    case 0: // TYPE_UNKNOWN :未知
                        break;
                    case 1: // TYPE_NONE
                        break;
                    case 2: // TYPE_LOCAL_DISK : 本地硬盘
                        FileSystemUsage usage = sigar.getFileSystemUsage(fs.getDirName());
                        fileMap.put("devName", fs.getDevName());
                        fileMap.put("dirName", fs.getDirName());
                        fileMap.put("flags", fs.getFlags());
                        fileMap.put("sysTypeName", fs.getSysTypeName());
                        fileMap.put("typeName", fs.getTypeName());
                        fileMap.put("type", fs.getType());
                        fileMap.put("total", usage.getTotal() / 1024L / 1024L);
                        fileMap.put("free", usage.getFree() / 1024L / 1024L);
                        fileMap.put("aVall", usage.getAvail() / 1024L / 1024L);//可用大小
                        fileMap.put("used", usage.getUsed() / 1024L / 1024L);
                        fileMap.put("usePercent", usage.getUsePercent() * 100D);
                        fileMap.put("diskRead", usage.getDiskReads());
                        fileMap.put("diskWrite", usage.getDiskWrites());
                        files.add(fileMap);
                        break;
                    case 3:// TYPE_NETWORK :网络
                        break;
                    case 4:// TYPE_RAM_DISK :闪存
                        break;
                    case 5:// TYPE_CDROM :光驱
                        break;
                    case 6:// TYPE_SWAP :页面交换
                        break;
                }
            }
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return files;
    }
    /**
     * 网络信息
     *
     * @throws Exception
     */
    public static Map<String, Object> net() {
        Map<String, Object> netMap = new HashMap<>();
        NetInterfaceConfig netConfig = null;
        try {
            netConfig = sigar.getNetInterfaceConfig();
            NetInterfaceStat netIfStat = sigar.getNetInterfaceStat(netConfig.getName());
            Map<String, Object> bps = populate(netConfig.getName());//bps
            netMap.put("address", netConfig.getAddress());
            netMap.put("broadcast", netConfig.getBroadcast());
            netMap.put("netmask", netConfig.getNetmask());
            netMap.put("rxPackets", netIfStat.getRxPackets());
            netMap.put("txPackets", netIfStat.getTxPackets());
            netMap.put("rxBytes", netIfStat.getRxBytes());
            netMap.put("txBytes", netIfStat.getTxBytes());
            netMap.put("txPackets", netIfStat.getTxPackets());
            netMap.put("txbps", bps.get("txbps"));
            netMap.put("rxbps", bps.get("rxbps"));
        } catch (SigarException e) {
            e.printStackTrace();
        }
        return netMap;
    }
    private static void ethernet() throws SigarException {
        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());//
        }
    }
    /**
     * 網絡傳輸速率 bps
     *
     * @param name
     * @throws SigarException
     */
    public static Map<String, Object> populate(String name)
            throws SigarException {
        Map<String, Object> bps = new HashMap<>();
        try {
            long start = System.currentTimeMillis();
            NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
            long rxBytesStart = statStart.getRxBytes();
            long txBytesStart = statStart.getTxBytes();
            Thread.sleep(1000);
            long end = System.currentTimeMillis();
            NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
            long rxBytesEnd = statEnd.getRxBytes();
            long txBytesEnd = statEnd.getTxBytes();
            long rxbps = ((rxBytesEnd - rxBytesStart) * 8 / 1024) / ((end - start) / 1000);
            long txbps = ((txBytesEnd - txBytesStart) * 8 / 1024) / ((end - start) / 1000);
            bps.put("rxbps", rxbps);
            bps.put("txbps", txbps);
            System.out.println("#######rxbps: " + rxbps + " txbps: " + txbps);
        } catch (SigarException e) {
        } catch (Exception e) {
        }
        return bps;
    }
    /**
     * 获取两位小数的double值
     * @param value
     * @return
     */
    public static double getDouble(double value){
        String total = String.format("%.2f", value );
        return Double.parseDouble(total);
    }
}

+ 1 - 2
src/main/java/com/yihu/hos/common/activeMq/ActivemqConfiguration.java

@ -1,7 +1,6 @@
package com.yihu.hos.common.activeMq;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@ -11,7 +10,7 @@ import javax.annotation.PostConstruct;
 * @vsrsion 1.0
 * Created at 2016/8/21.
 */
@Configuration
//@Configuration
public class ActivemqConfiguration {
    @Value("${spring.activemq.broker-url}")
    private String brokerURL;

+ 1 - 1
src/main/java/com/yihu/hos/filter/HibernateFilter.java

@ -1,6 +1,6 @@
package com.yihu.hos.filter;
import org.springframework.orm.hibernate5.support.OpenSessionInViewFilter;
import org.springframework.orm.hibernate4.support.OpenSessionInViewFilter;
import javax.servlet.annotation.WebFilter;

+ 80 - 0
src/main/java/com/yihu/hos/scheduler/EnvScheduler.java

@ -0,0 +1,80 @@
package com.yihu.hos.scheduler;
import com.yihu.hos.common.MongodbUtil;
import com.yihu.hos.common.SigarUtil;
import com.yihu.hos.core.datatype.DateUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.crawler.service.DataCollectDispatcher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 *  服务器性能数据采集定时器
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/11.
 */
@Component
public class EnvScheduler {
    private static Logger logger = LoggerFactory.getLogger(EnvScheduler.class);
    private static DataCollectDispatcher dispatch = DataCollectDispatcher.getInstance();
    @Scheduled(cron="0 0/1 * * * ?") //每分钟执行一次
    public void statusCheck() {
        System.out.println("每分钟执行一次。开始============================================");
        //TODO 采集服务器健康监控指标数据 statusTask.healthCheck();
        collectEnvHealth();
        System.out.println("每分钟执行一次。结束。");
    }
    public String collectEnvHealth(){
        MongodbUtil monoEnv = new MongodbUtil("envHealth");
        try {
            JSONObject result = new JSONObject();
            result.put("create_date", DateUtil.getCurrentString(DateUtil.DEFAULT_YMDHMSDATE_FORMAT));
            //cpu
            JSONObject cpu = JSONObject.fromObject( SigarUtil.cpu());
            result.put("data",cpu);
            monoEnv.insert("cpu",result);
            //内存
            JSONObject memory = JSONObject.fromObject( SigarUtil.memory());
            result.put("data",memory);
            monoEnv.insert("memory",result);
            //硬盘
            List<JSONObject> files = JSONArray.fromObject( SigarUtil.file());
            result.put("data",files);
            monoEnv.insert("files", result);
            //网络
            JSONObject net = JSONObject.fromObject( SigarUtil.net());
            result.put("data",net);
            monoEnv.insert("net",result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
//    @Scheduled(fixedRate=10000)
//    public void testTasks() {
//        System.out.println("每10秒执行一次。开始……");
//        //statusTask.healthCheck();
//        System.out.println("每10秒执行一次。结束。");
//    }
}

+ 86 - 0
src/main/java/com/yihu/hos/server/controller/ServerMetricsController.java

@ -0,0 +1,86 @@
package com.yihu.hos.server.controller;
import com.yihu.hos.server.service.ServerMetricsService;
import com.yihu.hos.web.framework.model.ActionResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hyperic.sigar.SigarException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 *  服务器健康监控
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/14.
 */
@RestController("ServerMetricsController")
@RequestMapping("/serverMetrics")
public class ServerMetricsController {
    @Autowired
    private ServerMetricsService serverMetricsService;
    @RequestMapping(value = "/searchHistory", method = RequestMethod.GET)
    @ApiOperation(value = "获取服务器历史监控数据", response = ActionResult.class, produces = "application/json", notes = "获取服务器历史监控数据")
    public ActionResult getHistory(
            @ApiParam(name = "type", value = "类型")
            @RequestParam(value = "type") String type,
            @ApiParam(name = "beginTime", value = "开始时间")
            @RequestParam(value = "beginTime", required = false) String beginTime,
            @ApiParam(name = "endTime", value = "结束时间")
            @RequestParam(value = "endTime", required = false) String endTime) {
        try {
            JSONArray data  = serverMetricsService.getHistory(type, beginTime, endTime);
            ActionResult result = new ActionResult(true,"查询成功");
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        ActionResult result = new ActionResult(false,"查询异常");
        return result;
    }
    @RequestMapping(value = "/searchCurrent", method = RequestMethod.GET)
    @ApiOperation(value = "获取服务器当前健康指标", response = ActionResult.class, produces = "application/json", notes = "获取服务器当前健康指标")
    public ActionResult searchCurrent(
            @ApiParam(name = "type", value = "类型")
            @RequestParam(value = "type") String type) {
        JSONObject data = null;
        try {
            data = serverMetricsService.getCurrent(type);
            ActionResult result = new ActionResult(true,"查询成功");
            result.setData(data);
            return result;
        } catch (SigarException e) {
            e.printStackTrace();
        }
        ActionResult result = new ActionResult(false,"查询异常");
        return result;
    }
    @RequestMapping(value = "/searchHardware", method = RequestMethod.GET)
    @ApiOperation(value = "获取服务器硬件信息", response = ActionResult.class, produces = "application/json", notes = "获取服务器硬件信息")
    public ActionResult searchHardware(
            @ApiParam(name = "type", value = "类型")
            @RequestParam(value = "type") String type) {
        //TODO 可以和上一個接口可共用
        return null;
    }
}

+ 107 - 0
src/main/java/com/yihu/hos/server/service/ServerMetricsService.java

@ -0,0 +1,107 @@
package com.yihu.hos.server.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.ehr.dbhelper.common.DBList;
import com.yihu.ehr.dbhelper.common.MongodbQuery;
import com.yihu.ehr.dbhelper.common.QueryCondition;
import com.yihu.ehr.dbhelper.common.QueryEntity;
import com.yihu.hos.common.SigarUtil;
import com.yihu.hos.crawler.model.transform.EhrCondition;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hyperic.sigar.SigarException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * 服务器指标 业务类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/10/14.
 */
@Component
public class ServerMetricsService {
    /**
     * 获取历史服务器监控指标
     *
     * @param type  监控类型(cpu,内存等)
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    public JSONArray getHistory(String type, String begin, String end) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JSONArray result = new JSONArray();
        List<EhrCondition> queryParams = new ArrayList<>();
        queryParams.add(new EhrCondition(" > ", "create_date", begin));
        queryParams.add(new EhrCondition(" < ", "create_date", end));
        result = collectionData(type, objectMapper.writeValueAsString(queryParams));
        return result;
    }
    /**
     * mongodb 查询方法
     *
     * @param tableCode
     * @param condition
     * @return
     * @throws Exception
     */
    public JSONArray collectionData(String tableCode, String condition) throws Exception {
        JSONArray result = new JSONArray();
        try {
            MongodbQuery mdb = new MongodbQuery("envHealth");//TODO 提取到配置文件中
            QueryEntity qe = new QueryEntity(tableCode);
            //设置参数
            if (!StringUtils.isEmpty(condition) && !"{}".equals(condition)) {
                JSONArray ar = JSONArray.fromObject(condition);
                for (int i = 0; i < ar.size(); i++) {
                    JSONObject jo = (JSONObject) ar.get(i);
                    String andOr = String.valueOf(jo.get("andOr"));
                    String field = String.valueOf(jo.get("field"));
                    String cond = String.valueOf(jo.get("condition"));
                    String value = String.valueOf(jo.get("value"));
                    qe.addCondition(new QueryCondition(andOr, cond, field, value));
                }
            }
            DBList list = mdb.query(qe);
            result = JSONArray.fromObject(list.getList().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 获取当前 服务器监控指标
     * @param type
     * @return
     * @throws SigarException
     */
    public JSONObject getCurrent(String type) throws SigarException {
        JSONObject result = new JSONObject();
        switch (type) {
            case "cpu" : // cpu
                result = JSONObject.fromObject(SigarUtil.cpu());
                break;
            case "memory" : // 内存
                result = JSONObject.fromObject(SigarUtil.memory());
                break;
            case "files" : // 硬盘
                result = JSONObject.fromObject(SigarUtil.file());
                break;
            case "net" :// 网络
                result = JSONObject.fromObject(SigarUtil.net());
                break;
        }
        return result;
    }
}

+ 1 - 1
src/main/resources/application.yml

@ -1,7 +1,7 @@
application:
  message: ESB
server:
  context-path: /
  context-path: /esb
  port: 8080
  session-timeout:  3000
security:

+ 22 - 0
src/main/resources/banner.txt

@ -0,0 +1,22 @@
                                            _ooOoo_
                                           o8888888o
                                           88" . "88
                                           (| -_- |)
                                            O\ = /O
                                        ____/`---'\____
                                      .   ' \\| |// `.
                                       / \\||| : |||// \
                                     / _||||| -:- |||||- \
                                       | | \\\ - /// | |
                                     | \_| ''\---/'' | |
                                      \ .-\__ `-` ___/-. /
                                   ___`. .' /--.--\ `. . __
                                ."" '< `.___\_<|>_/___.' >'"".
                               | | : `- \`.;`\ _ /`;.`/ - ` : | |
                                 \ \ `-. \_ __\ /__ _/ .-` / /
                         ======`-.____`-.___\_____/___.-`____.-'======
                                            `=---='
                         .............................................
                         佛祖保佑                               永无BUG
**************************spring-boot.version: ${spring-boot.version}*****************************

BIN
src/main/resources/libsigar-amd64-linux.so


BIN
src/main/resources/sigar-amd64-winnt.dll


+ 3 - 3
src/main/resources/spring/applicationContext.xml

@ -50,7 +50,7 @@
    </bean>
    <!--Hibernate 会话管理器配置-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
@ -74,7 +74,7 @@
    </bean>
    <!-- 将多个配置文件读取到容器中,交给Spring管理 -->
    <!--Hibernate 事务配置-->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
@ -104,7 +104,7 @@
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--Hibernate模版配置 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" scope="singleton">-->