目前Java web应用中大规模使用分布式系统和集群,集群中存在多台服务器对外提供服务,那么就存在一个问题,如何确定一个请求应该分发到哪台服务器上呢,这就需要获取当前服务器CPU、内存、网络、文件句柄的使用情况,合理分发请求,以使集群中所有服务器达到负载均衡的效果。
获取CPU利用率
通过使用java.lang.Runtime类执行cat /proc/stat命令获取Cpu时钟数据,进行Cpu利用率计算。“proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间。它以文件系统的方式为访问系统内核数据的操作提供接口。用户和应用程序可以通过proc得到系统的信息,并可以改变内核的某些参数。” 因此,程序在从/proc/stat中获取Cpu指标时,不会发生磁盘I/O,计算Cpu使用率的实时性更强,计算结果更可靠。[
参数解释]
参考地址:
http://blog.csdn.net/blue_jjw/article/details/8741000
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| package com.oracle.jvm.load;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
* @auth zhengzhi.ren * @date 2015/7/25. */ public class CpuMonitor {
private static final String IDLE_TIME = "idleTime";
private static final String TOTAL_TIME = "totalTime";
private static final String command = "cat /proc/stat";
private Long intervalSecond = 60L;
public Map<String, Long> process() throws IOException { System.out.println("Start to collect usage of cpu."); Process process = null; BufferedReader reader = null; Map<String, Long> cpuLoad = new ConcurrentHashMap<String, Long>(1); try { Runtime runtime = Runtime.getRuntime(); process = runtime.exec(command); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); Long idleTime = 0L; Long totalCpuTime = 0L; String data = null; String[] load = null; while ((data = reader.readLine()) != null) { if (!data.startsWith("cpu")) { continue; } data = data.trim(); System.out.println("The current information of cpu:" + data); load = data.split("\\s+"); idleTime = Long.parseLong(load[4]); for (String info : load) { if ("cpu".equals(info)){ continue; } totalCpuTime += Long.parseLong(info); } break; } cpuLoad.put(IDLE_TIME, idleTime); cpuLoad.put(TOTAL_TIME, totalCpuTime); } finally { reader.close(); process.destroy(); } System.out.println("Collect usage of cpu end."); return cpuLoad; }
* compute usage rate of cpu * @return */ public double getCpuUsageRate() throws IOException, InterruptedException { Map<String, Long> firesClock = process(); Thread.sleep(intervalSecond); Map<String, Long> lastClock = process(); Long firstIdleTime = firesClock.get(IDLE_TIME); Long lastIdleTime = lastClock.get(TOTAL_TIME); Long firstTotalTime = firesClock.get(IDLE_TIME); Long lastTotalTime = lastClock.get(TOTAL_TIME); return 1 - (float)(lastIdleTime - firstIdleTime)/(float)(lastTotalTime - firstTotalTime); } }
|
原创技术文章,转载请注明:转自http://newliferen.github.io/