SpringBoot 封装Windows 性能监控分析

访客 阅读:252 2021-03-31 21:06:29 评论:0

整体项目结构:

BlueSky 的pom.xml 文件:

<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"> 
	<modelVersion>4.0.0</modelVersion> 
	<groupId>com.zzg</groupId> 
	<artifactId>BuleSky</artifactId> 
	<version>0.0.1-SNAPSHOT</version> 
	<packaging>pom</packaging> 
 
	<!--springboot 父类 --> 
	<parent> 
		<groupId>org.springframework.boot</groupId> 
		<artifactId>spring-boot-starter-parent</artifactId> 
		<version>2.1.0.RELEASE</version> 
	</parent> 
 
	<properties> 
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
		<java.version>1.8</java.version> 
	</properties> 
 
	<dependencies> 
		<!--springboot 依赖web --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-web</artifactId> 
		</dependency> 
		<!--springboot 依赖test --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-test</artifactId> 
		</dependency> 
		<!--springboot 依赖devtool --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-devtools</artifactId> 
		</dependency> 
		<!--lombak 集成 --> 
		<dependency> 
			<groupId>org.projectlombok</groupId> 
			<artifactId>lombok</artifactId> 
			<version>1.18.0</version> 
		</dependency> 
		<!--apache common 工具包 --> 
		<dependency> 
			<groupId>commons-net</groupId> 
			<artifactId>commons-net</artifactId> 
			<version>3.6</version> 
		</dependency> 
		 <dependency> 
            <groupId>org.apache.commons</groupId> 
            <artifactId>commons-lang3</artifactId> 
            <version>3.8.1</version> 
        </dependency> 
	</dependencies> 
	<modules> 
		<module>common-ssh</module> 
		<module>common-ftp</module> 
		<module>common-fastdfs</module> 
		<module>common-monitor-windows</module> 
		<module>common-monitor_linux</module> 
		<module>common-elasticsearch</module> 
	</modules> 
</project>

common-monitor-windows 项目结构:

Application.java

package com.zzg.common; 
 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
 
@SpringBootApplication 
public class Application { 
 
	public static void main(String[] args) { 
		// TODO Auto-generated method stub 
		SpringApplication.run(Application.class, args); 
	} 
 
} 

Cpu.java

package com.zzg.common.entity; 
 
 
import com.zzg.common.util.Arith; 
 
import lombok.Getter; 
import lombok.Setter; 
 
public class Cpu { 
	/** 
     * 核心数 
     */ 
	@Getter 
	@Setter 
    private int cpuNum; 
 
    /** 
     * CPU总的使用率 
     */ 
	@Setter 
    private double total; 
 
    /** 
     * CPU系统使用率 
     */ 
	@Setter 
    private double sys; 
 
    /** 
     * CPU用户使用率 
     */ 
	@Setter 
    private double used; 
 
    /** 
     * CPU当前等待率 
     */ 
	@Setter 
    private double wait; 
 
    /** 
     * CPU当前空闲率 
     */ 
	@Setter 
    private double free; 
 
 
    public double getTotal() { 
        return Arith.round(Arith.mul(total, 100), 2); 
    } 
 
    public double getSys() { 
        return Arith.round(Arith.mul(sys / total, 100), 2); 
    } 
     
    public double getUsed() { 
        return Arith.round(Arith.mul(used / total, 100), 2); 
    } 
 
    public double getWait() { 
        return Arith.round(Arith.mul(wait / total, 100), 2); 
    } 
 
    public double getFree() { 
        return Arith.round(Arith.mul(free / total, 100), 2); 
    } 
} 

Jvm.java

package com.zzg.common.entity; 
 
import java.lang.management.ManagementFactory; 
import com.zzg.common.util.Arith; 
import com.zzg.common.util.DateUtils; 
 
import lombok.Getter; 
import lombok.Setter; 
 
 
/** 
 * 虚拟机相关设置 
 * @author zzg 
 * 
 */ 
public class Jvm { 
	/** 
     * 当前JVM占用的内存总数(M) 
     */ 
	@Setter 
    private double total; 
 
    /** 
     * JVM最大可用内存总数(M) 
     */ 
	@Setter 
    private double max; 
 
    /** 
     * JVM空闲内存(M) 
     */ 
	@Setter 
    private double free; 
 
    /** 
     * JDK版本 
     */ 
	@Getter 
	@Setter 
    private String version; 
 
    /** 
     * JDK路径 
     */ 
	@Getter 
	@Setter 
    private String home; 
 
    public double getTotal() { 
        return Arith.div(total, (1024 * 1024), 2); 
    } 
 
    public double getMax() { 
        return Arith.div(max, (1024 * 1024), 2); 
    } 
 
    public double getFree() { 
        return Arith.div(free, (1024 * 1024), 2); 
    } 
 
    public double getUsed() { 
        return Arith.div(total - free, (1024 * 1024), 2); 
    } 
 
    public double getUsage() { 
        return Arith.mul(Arith.div(total - free, total, 4), 100); 
    } 
 
    /** 
     * 获取JDK名称 
     */ 
    public String getName() { 
        return ManagementFactory.getRuntimeMXBean().getVmName(); 
    } 
 
    /** 
     * JDK启动时间 
     */ 
    public String getStartTime() { 
        return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate()); 
    } 
 
    /** 
     * JDK运行时间 
     */ 
    public String getRunTime() { 
        return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate()); 
    } 
} 

Mem.java

package com.zzg.common.entity; 
 
import com.zzg.common.util.Arith; 
 
import lombok.Setter; 
 
/** 
 * 内存相关信息 
 * @author zzg 
 * 
 */ 
public class Mem { 
	/** 
     * 内存总量 
     */ 
	@Setter 
    private double total; 
 
    /** 
     * 已用内存 
     */ 
	@Setter 
    private double used; 
 
    /** 
     * 剩余内存 
     */ 
	@Setter 
    private double free; 
 
    public double getTotal() { 
        return Arith.div(total, (1024 * 1024 * 1024), 2); 
    } 
 
    public double getUsed() { 
        return Arith.div(used, (1024 * 1024 * 1024), 2); 
    } 
 
    public double getFree() { 
        return Arith.div(free, (1024 * 1024 * 1024), 2); 
    } 
 
    public double getUsage() { 
        return Arith.mul(Arith.div(used, total, 4), 100); 
    } 
} 

Sys.java

package com.zzg.common.entity; 
 
import lombok.Getter; 
import lombok.Setter; 
 
/** 
 * 系统相关信息 
 * @author zzg 
 * 
 */ 
public class Sys { 
	/** 
     * 服务器名称 
     */ 
	@Getter 
	@Setter 
    private String computerName; 
 
    /** 
     * 服务器Ip 
     */ 
	@Getter 
	@Setter 
    private String computerIp; 
 
    /** 
     * 项目路径 
     */ 
	@Getter 
	@Setter 
    private String userDir; 
 
    /** 
     * 操作系统 
     */ 
	@Getter 
	@Setter 
    private String osName; 
 
    /** 
     * 系统架构 
     */ 
	@Getter 
	@Setter 
    private String osArch;		 
} 

SysFile.java

package com.zzg.common.entity; 
 
import lombok.Getter; 
import lombok.Setter; 
 
/** 
 * 系统文件相关信息 
 * @author zzg 
 * 
 */ 
public class SysFile { 
	 /** 
     * 盘符路径 
     */ 
	@Getter 
	@Setter 
    private String dirName; 
 
    /** 
     * 盘符类型 
     */ 
	@Getter 
	@Setter 
    private String sysTypeName; 
 
    /** 
     * 文件类型 
     */ 
	@Getter 
	@Setter 
    private String typeName; 
 
    /** 
     * 总大小 
     */ 
	@Getter 
	@Setter 
    private String total; 
 
    /** 
     * 剩余大小 
     */ 
	@Getter 
	@Setter 
    private String free; 
 
    /** 
     * 已经使用量 
     */ 
	@Getter 
	@Setter 
    private String used; 
 
    /** 
     * 资源的使用率 
     */ 
	@Getter 
	@Setter 
    private double usage; 
} 

Server.java

package com.zzg.common.server; 
 
import java.io.Serializable; 
import java.net.UnknownHostException; 
import java.util.LinkedList; 
import java.util.List; 
import java.util.Properties; 
 
import com.zzg.common.entity.Cpu; 
import com.zzg.common.entity.Jvm; 
import com.zzg.common.entity.Mem; 
import com.zzg.common.entity.Sys; 
import com.zzg.common.entity.SysFile; 
import com.zzg.common.util.Arith; 
import com.zzg.common.util.IpUtils; 
 
import lombok.Getter; 
import lombok.Setter; 
import oshi.SystemInfo; 
import oshi.hardware.CentralProcessor; 
import oshi.hardware.GlobalMemory; 
import oshi.hardware.HardwareAbstractionLayer; 
import oshi.hardware.CentralProcessor.TickType; 
import oshi.software.os.FileSystem; 
import oshi.software.os.OSFileStore; 
import oshi.software.os.OperatingSystem; 
import oshi.util.Util; 
 
public class Server implements Serializable { 
 
	/** 
	 *  
	 */ 
	private static final long serialVersionUID = 1L; 
 
	private static final int OSHI_WAIT_SECOND = 1000; 
 
	/** 
	 * CPU相关信息 
	 */ 
	@Getter 
	@Setter 
	private Cpu cpu = new Cpu(); 
 
	/** 
	 * 內存相关信息 
	 */ 
	@Getter 
	@Setter 
	private Mem mem = new Mem(); 
 
	/** 
	 * JVM相关信息 
	 */ 
	@Getter 
	@Setter 
	private Jvm jvm = new Jvm(); 
 
	/** 
	 * 服务器相关信息 
	 */ 
	@Getter 
	@Setter 
	private Sys sys = new Sys(); 
 
	/** 
	 * 磁盘相关信息 
	 */ 
	@Getter 
	@Setter 
	private List<SysFile> sysFiles = new LinkedList<SysFile>(); 
	 
 
	 public void copyTo() throws Exception { 
	        SystemInfo si = new SystemInfo(); 
	        HardwareAbstractionLayer hal = si.getHardware(); 
 
	        setCpuInfo(hal.getProcessor()); 
 
	        setMemInfo(hal.getMemory()); 
 
	        setSysInfo(); 
 
	        setJvmInfo(); 
 
	        setSysFiles(si.getOperatingSystem()); 
	    } 
 
	    /** 
	     * 设置CPU信息 
	     */ 
	    private void setCpuInfo(CentralProcessor processor) { 
	        // CPU信息 
	        long[] prevTicks = processor.getSystemCpuLoadTicks(); 
	        Util.sleep(OSHI_WAIT_SECOND); 
	        long[] ticks = processor.getSystemCpuLoadTicks(); 
	        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; 
	        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; 
	        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; 
	        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; 
	        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; 
	        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; 
	        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; 
	        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; 
	        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; 
	        cpu.setCpuNum(processor.getLogicalProcessorCount()); 
	        cpu.setTotal(totalCpu); 
	        cpu.setSys(cSys); 
	        cpu.setUsed(user); 
	        cpu.setWait(iowait); 
	        cpu.setFree(idle); 
	    } 
 
	    /** 
	     * 设置内存信息 
	     */ 
	    private void setMemInfo(GlobalMemory memory) { 
	        mem.setTotal(memory.getTotal()); 
	        mem.setUsed(memory.getTotal() - memory.getAvailable()); 
	        mem.setFree(memory.getAvailable()); 
	    } 
 
	    /** 
	     * 设置服务器信息 
	     */ 
	    private void setSysInfo() { 
	        Properties props = System.getProperties(); 
	        sys.setComputerName(IpUtils.getHostName()); 
	        sys.setComputerIp(IpUtils.getHostIp()); 
	        sys.setOsName(props.getProperty("os.name")); 
	        sys.setOsArch(props.getProperty("os.arch")); 
	        sys.setUserDir(props.getProperty("user.dir")); 
	    } 
 
	    /** 
	     * 设置Java虚拟机 
	     */ 
	    private void setJvmInfo() throws UnknownHostException { 
	        Properties props = System.getProperties(); 
	        jvm.setTotal(Runtime.getRuntime().totalMemory()); 
	        jvm.setMax(Runtime.getRuntime().maxMemory()); 
	        jvm.setFree(Runtime.getRuntime().freeMemory()); 
	        jvm.setVersion(props.getProperty("java.version")); 
	        jvm.setHome(props.getProperty("java.home")); 
	    } 
 
	    /** 
	     * 设置磁盘信息 
	     */ 
	    private void setSysFiles(OperatingSystem os) { 
	        FileSystem fileSystem = os.getFileSystem(); 
	        OSFileStore[] fsArray = fileSystem.getFileStores(); 
	        for (OSFileStore fs : fsArray) { 
	            long free = fs.getUsableSpace(); 
	            long total = fs.getTotalSpace(); 
	            long used = total - free; 
	            SysFile sysFile = new SysFile(); 
	            sysFile.setDirName(fs.getMount()); 
	            sysFile.setSysTypeName(fs.getType()); 
	            sysFile.setTypeName(fs.getName()); 
	            sysFile.setTotal(convertFileSize(total)); 
	            sysFile.setFree(convertFileSize(free)); 
	            sysFile.setUsed(convertFileSize(used)); 
	            sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100)); 
	            sysFiles.add(sysFile); 
	        } 
	    } 
 
	    /** 
	     * 字节转换 
	     * 
	     * @param size 字节大小 
	     * @return 转换后值 
	     */ 
	    public String convertFileSize(long size) { 
	        long kb = 1024; 
	        long mb = kb * 1024; 
	        long gb = mb * 1024; 
	        if (size >= gb) { 
	            return String.format("%.1f GB" , (float) size / gb); 
	        } else if (size >= mb) { 
	            float f = (float) size / mb; 
	            return String.format(f > 100 ? "%.0f MB" : "%.1f MB" , f); 
	        } else if (size >= kb) { 
	            float f = (float) size / kb; 
	            return String.format(f > 100 ? "%.0f KB" : "%.1f KB" , f); 
	        } else { 
	            return String.format("%d B" , size); 
	        } 
	    } 
} 

Arith.java

package com.zzg.common.util; 
 
import java.math.BigDecimal; 
 
/** 
 * 精度计算工具 
 * @author zzg 
 * 
 */ 
public class Arith { 
	 /** 
     * 默认除法运算精度 
     */ 
    private static final int DEF_DIV_SCALE = 10; 
 
    /** 
     * 这个类不能实例化 
     */ 
    private Arith() { 
    } 
 
    /** 
     * 提供精确的加法运算。 
     * 
     * @param v1 被加数 
     * @param v2 加数 
     * @return 两个参数的和 
     */ 
    public static double add(double v1, double v2) { 
        BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2)); 
        return b1.add(b2).doubleValue(); 
    } 
 
    /** 
     * 提供精确的减法运算。 
     * 
     * @param v1 被减数 
     * @param v2 减数 
     * @return 两个参数的差 
     */ 
    public static double sub(double v1, double v2) { 
        BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2)); 
        return b1.subtract(b2).doubleValue(); 
    } 
 
    /** 
     * 提供精确的乘法运算。 
     * 
     * @param v1 被乘数 
     * @param v2 乘数 
     * @return 两个参数的积 
     */ 
    public static double mul(double v1, double v2) { 
        BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2)); 
        return b1.multiply(b2).doubleValue(); 
    } 
 
    /** 
     * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 
     * 小数点以后10位,以后的数字四舍五入。 
     * 
     * @param v1 被除数 
     * @param v2 除数 
     * @return 两个参数的商 
     */ 
    public static double div(double v1, double v2) { 
        return div(v1, v2, DEF_DIV_SCALE); 
    } 
 
    /** 
     * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 
     * 定精度,以后的数字四舍五入。 
     * 
     * @param v1    被除数 
     * @param v2    除数 
     * @param scale 表示表示需要精确到小数点以后几位。 
     * @return 两个参数的商 
     */ 
    public static double div(double v1, double v2, int scale) { 
        if (scale < 0) { 
            throw new IllegalArgumentException( 
                    "The scale must be a positive integer or zero"); 
        } 
        BigDecimal b1 = new BigDecimal(Double.toString(v1)); 
        BigDecimal b2 = new BigDecimal(Double.toString(v2)); 
        if (BigDecimal.ZERO.compareTo(b1.multiply(b2)) == 0){ 
            return BigDecimal.ZERO.doubleValue(); 
        } 
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); 
    } 
 
    /** 
     * 提供精确的小数位四舍五入处理。 
     * 
     * @param v     需要四舍五入的数字 
     * @param scale 小数点后保留几位 
     * @return 四舍五入后的结果 
     */ 
    public static double round(double v, int scale) { 
        if (scale < 0) { 
            throw new IllegalArgumentException( 
                    "The scale must be a positive integer or zero"); 
        } 
        BigDecimal b = new BigDecimal(Double.toString(v)); 
        BigDecimal one = new BigDecimal("1"); 
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); 
    } 
} 

DateUtils.java

package com.zzg.common.util; 
 
import java.lang.management.ManagementFactory; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import org.apache.commons.lang3.ObjectUtils; 
import org.apache.commons.lang3.time.DateFormatUtils; 
 
/** 
 * 时间工具类 
 * @author zzg 
 * 
 */ 
public class DateUtils extends org.apache.commons.lang3.time.DateUtils { 
	public static final String YYYY = "yyyy" ; 
 
    public static final String YYYY_MM = "yyyy-MM" ; 
 
    public static final String YYYY_MM_DD = "yyyy-MM-dd" ; 
 
    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss" ; 
 
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss" ; 
 
    private static String[] parsePatterns = { 
            YYYY_MM_DD , YYYY_MM_DD_HH_MM_SS , "yyyy-MM-dd HH:mm" , YYYY_MM , 
            "yyyy/MM/dd" , "yyyy/MM/dd HH:mm:ss" , "yyyy/MM/dd HH:mm" , "yyyy/MM" , 
            "yyyy.MM.dd" , "yyyy.MM.dd HH:mm:ss" , "yyyy.MM.dd HH:mm" , "yyyy.MM"}; 
 
    /** 
     * 获取当前Date型日期 
     * 
     * @return Date() 当前日期 
     */ 
    public static Date getNowDate() { 
        return new Date(); 
    } 
 
    /** 
     * 获取当前日期, 默认格式为yyyy-MM-dd 
     * 
     * @return String 
     */ 
    public static String getDate() { 
        return dateTimeNow(YYYY_MM_DD); 
    } 
 
    public static final String getTime() { 
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS); 
    } 
 
    public static final String dateTimeNow() { 
        return dateTimeNow(YYYYMMDDHHMMSS); 
    } 
 
    public static final String dateTimeNow(final String format) { 
        return parseDateToStr(format, new Date()); 
    } 
 
    public static final String dateTime(final Date date) { 
        return parseDateToStr(YYYY_MM_DD, date); 
    } 
 
    public static final String parseDateToStr(final String format, final Date date) { 
        if(ObjectUtils.allNotNull(date)){ 
            return new SimpleDateFormat(format).format(date); 
        } 
        return null; 
    } 
 
 
    /** 
     * 日期路径 即年/月/日 如2018/08/08 
     */ 
    public static final String datePath() { 
        Date now = new Date(); 
        return DateFormatUtils.format(now, "yyyy/MM/dd"); 
    } 
 
    /** 
     * 日期路径 即年/月/日 如20180808 
     */ 
    public static final String dateTime() { 
        Date now = new Date(); 
        return DateFormatUtils.format(now, "yyyyMMdd"); 
    } 
 
    /** 
     * 日期型字符串转化为日期 格式 
     */ 
    public static Date parseDate(Object str) { 
        if (str == null) { 
            return null; 
        } 
        try { 
            return parseDate(str.toString(), parsePatterns); 
        } catch (ParseException e) { 
            return null; 
        } 
    } 
 
    /** 
     * 获取服务器启动时间 
     */ 
    public static Date getServerStartDate() { 
        long time = ManagementFactory.getRuntimeMXBean().getStartTime(); 
        return new Date(time); 
    } 
 
    /** 
     * 计算两个时间差 
     */ 
    public static String getDatePoor(Date endDate, Date nowDate) { 
        long nd = (long)1000 * 24 * 60 * 60; 
        long nh = (long)1000 * 60 * 60; 
        long nm = (long)1000 * 60; 
        // 获得两个时间的毫秒时间差异 
        long diff = endDate.getTime() - nowDate.getTime(); 
        // 计算差多少天 
        long day = diff / nd; 
        // 计算差多少小时 
        long hour = diff % nd / nh; 
        // 计算差多少分钟 
        long min = diff % nd % nh / nm; 
        // 计算差多少秒//输出结果 
        return day + "天" + hour + "小时" + min + "分钟" ; 
    } 
} 

IpUtils.java

package com.zzg.common.util; 
 
import java.net.InetAddress; 
import java.net.UnknownHostException; 
import javax.servlet.http.HttpServletRequest; 
 
 
import lombok.extern.slf4j.Slf4j; 
 
@Slf4j 
public class IpUtils { 
	public static final String LOCAL_IP="127.0.0.1"; 
	 
	 private IpUtils(){ 
	        throw new IllegalStateException("Utility class"); 
	    } 
	    public static String getIpAddr(HttpServletRequest request) { 
	        String unknown = "unknown"; 
	        if (request == null) { 
	            return unknown; 
	        } 
	        String ip = request.getHeader("x-forwarded-for"); 
	        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { 
	            ip = request.getHeader("Proxy-Client-IP"); 
	        } 
	        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { 
	            ip = request.getHeader("X-Forwarded-For"); 
	        } 
	        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { 
	            ip = request.getHeader("WL-Proxy-Client-IP"); 
	        } 
	        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { 
	            ip = request.getHeader("X-Real-IP"); 
	        } 
 
	        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { 
	            ip = request.getRemoteAddr(); 
	        } 
 
	        return "0:0:0:0:0:0:0:1".equals(ip) ? LOCAL_IP : ip; 
	    } 
 
	    public static boolean internalIp(String ip) { 
	        byte[] addr = textToNumericFormatV4(ip); 
	        return internalIp(addr) || LOCAL_IP.equals(ip); 
	    } 
 
	    private static boolean internalIp(byte[] addr) { 
	        if(addr == null || addr.length<1){ 
	            return false; 
	        } 
	        final byte b0 = addr[0]; 
	        final byte b1 = addr[1]; 
	        // 10.x.x.x/8 
	        final byte section1 = 0x0A; 
	        // 172.16.x.x/12 
	        final byte section2 = (byte) 0xAC; 
	        final byte section3 = (byte) 0x10; 
	        final byte section4 = (byte) 0x1F; 
	        // 192.168.x.x/16 
	        final byte section5 = (byte) 0xC0; 
	        final byte section6 = (byte) 0xA8; 
	        switch (b0) { 
	            case section1: 
	                return true; 
	            case section2: 
	                if (b1 >= section3 && b1 <= section4) { 
	                    return true; 
	                }else { 
	                    return false; 
	                } 
	            case section5: 
	                if(b1 == section6){ 
	                    return true; 
	                }else { 
	                    return false; 
	                } 
	            default: 
	                return false; 
	        } 
	    } 
 
	    /** 
	     * 将IPv4地址转换成字节 
	     * 
	     * @param text IPv4地址 
	     * @return byte 字节 
	     */ 
	    public static byte[] textToNumericFormatV4(String text) { 
	        byte[] emptyByte = new byte[0]; 
	        if (text.length() == 0) { 
	            return emptyByte; 
	        } 
 
	        byte[] bytes = new byte[4]; 
	        String[] elements = text.split("\\.", -1); 
	        try { 
	            long l; 
	            int i; 
	            switch (elements.length) { 
	                case 1: 
	                    l = Long.parseLong(elements[0]); 
	                    if ((l < 0L) || (l > 4294967295L)) { 
	                        return emptyByte; 
	                    } 
	                    bytes[0] = (byte) (int) (l >> 24 & 0xFF); 
	                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); 
	                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); 
	                    bytes[3] = (byte) (int) (l & 0xFF); 
	                    break; 
	                case 2: 
	                    l = Integer.parseInt(elements[0]); 
	                    if ((l < 0L) || (l > 255L)) { 
	                        return emptyByte; 
	                    } 
	                    bytes[0] = (byte) (int) (l & 0xFF); 
	                    l = Integer.parseInt(elements[1]); 
	                    if ((l < 0L) || (l > 16777215L)) { 
	                        return emptyByte; 
	                    } 
	                    bytes[1] = (byte) (int) (l >> 16 & 0xFF); 
	                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); 
	                    bytes[3] = (byte) (int) (l & 0xFF); 
	                    break; 
	                case 3: 
	                    for (i = 0; i < 2; ++i) { 
	                        l = Integer.parseInt(elements[i]); 
	                        if ((l < 0L) || (l > 255L)) { 
	                            return emptyByte; 
	                        } 
	                        bytes[i] = (byte) (int) (l & 0xFF); 
	                    } 
	                    l = Integer.parseInt(elements[2]); 
	                    if ((l < 0L) || (l > 65535L)) { 
	                        return emptyByte; 
	                    } 
	                    bytes[2] = (byte) (int) (l >> 8 & 0xFF); 
	                    bytes[3] = (byte) (int) (l & 0xFF); 
	                    break; 
	                case 4: 
	                    for (i = 0; i < 4; ++i) { 
	                        l = Integer.parseInt(elements[i]); 
	                        if ((l < 0L) || (l > 255L)) { 
	                            return emptyByte; 
	                        } 
	                        bytes[i] = (byte) (int) (l & 0xFF); 
	                    } 
	                    break; 
	                default: 
	                    return emptyByte; 
	            } 
	        } catch (NumberFormatException e) { 
	            return emptyByte; 
	        } 
	        return bytes; 
	    } 
 
	    public static String getHostIp() { 
	        try { 
	            return InetAddress.getLocalHost().getHostAddress(); 
	        } catch (UnknownHostException e) { 
	            log.error(e.getMessage(), e); 
	        } 
	        return "127.0.0.1"; 
	    } 
 
	    public static String getHostName() { 
	        try { 
	            return InetAddress.getLocalHost().getHostName(); 
	        } catch (UnknownHostException e) { 
	            log.error(e.getMessage(), e); 
	        } 
	        return "未知"; 
	    } 
} 

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号