import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.util.HashMap;
import java.util.Map;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeDataSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tuniu.myMonitor.dataCollection.IDataCollection;
import com.tuniu.myMonitor.protocol.Performance.GCInfo;
import com.tuniu.myMonitor.protocol.Performance.PerformanceBean;
import com.tuniu.myMonitor.utils.CommonConstants;
import com.tuniu.myMonitor.utils.CommonUtils;
public class DataCollectionImpl implements IDataCollection{
private static final Logger LOGGER = LoggerFactory
.getLogger(DataCollectionImpl.class);
private static final String SERVICE_URL = new StringBuffer(CommonConstants.RMI_PREFIX)
.append(CommonConstants.RMI_HOST).append(CommonConstants.RMI_PORT).append(CommonConstants.RMI_SUFFIX)
.toString();
public PerformanceBean collectPerformanceInfo() {
long startTime = System.currentTimeMillis();
MBeanServerConnection mBeanSConnection = null;
MemoryUsage heapMemoryUsage = null;
MemoryUsage nonHeapMemoryUsage = null;
OperatingSystemMXBean osInfo = null;
Map<String, String> gcInfo = null;
try {
mBeanSConnection = CommonUtils.getMBeanSConnector(SERVICE_URL);
heapMemoryUsage = getMemoryUsage(mBeanSConnection, CommonConstants.HEAPMEMORYUSAGE_ATTRIBUTE_NAME);
nonHeapMemoryUsage = getMemoryUsage(mBeanSConnection, CommonConstants.NONHEAPMEMORYUSAGE_ATTRIBUTE_NAME);
osInfo = getOSInfo(mBeanSConnection);
gcInfo = getJstatFields();
} catch (Exception e) {
// TODO
e.printStackTrace();
}
if (isNotNull(mBeanSConnection, heapMemoryUsage, nonHeapMemoryUsage, osInfo, gcInfo)) {
// TODO add log
return null;
}
PerformanceBean performBean = null;
performBean = PerformanceBean
.newBuilder()
.setArch(osInfo.getArch())
.setAvailableProcessors(osInfo.getAvailableProcessors())
.setOsName(osInfo.getName())
.setSystemLoadAverage(osInfo.getSystemLoadAverage())
.setCommittedHeap(heapMemoryUsage.getCommitted())
.setInitHeap(heapMemoryUsage.getInit())
.setUsedHeap(heapMemoryUsage.getUsed())
.setMaxHeap(heapMemoryUsage.getMax())
.setInitNonHeap(nonHeapMemoryUsage.getInit())
.setCommittedNonHeap(nonHeapMemoryUsage.getCommitted())
.setUsedNonHeap(nonHeapMemoryUsage.getUsed())
.setMaxNonHeap(nonHeapMemoryUsage.getMax())
.setGc(GCInfo.newBuilder().setJstatS0(Double.valueOf(gcInfo.get(CommonConstants.S0)))
.setJstatS1(Double.valueOf(gcInfo.get(CommonConstants.S1)))
.setJstatE(Double.valueOf(gcInfo.get(CommonConstants.E)))
.setJstatO(Double.valueOf(gcInfo.get(CommonConstants.O)))
.setJstatP(Double.valueOf(gcInfo.get(CommonConstants.P)))
.setJstatYGC(Double.valueOf(gcInfo.get(CommonConstants.YGC)))
.setJstatYGCT(Double.valueOf(gcInfo.get(CommonConstants.YGCT)))
.setJstatFGC(Double.valueOf(gcInfo.get(CommonConstants.FGC)))
.setJstatFGCT(Double.valueOf(gcInfo.get(CommonConstants.FGCT)))
.setJstatGCT(Double.valueOf(gcInfo.get(CommonConstants.GCT)))).build();
LOGGER.info("cost:{}", System.currentTimeMillis() - startTime);
// ObjectMapper mapper = new ObjectMapper();
// mapper.writeValue(new
// File("D:\\Users\\zhangshuo\\Desktop\\perBean.json"), perfBean);
//
// mapper.defaultPrettyPrintingWriter().writeValue(new
// File("D:\\Users\\zhangshuo\\Desktop\\perBean.json"), performBean);
return performBean;
}
//TODO refactor with JMX Proxy
private MemoryUsage getMemoryUsage(MBeanServerConnection mBeanSConnection,String attribute) throws Exception{
MemoryUsage heapMemoryUsage = null;
ObjectName heapObjName = new ObjectName(CommonConstants.MEMORY_OBJECT_NAME);
heapObjName = new ObjectName(CommonConstants.MEMORY_OBJECT_NAME);
heapMemoryUsage = MemoryUsage.from((CompositeDataSupport) mBeanSConnection.getAttribute(heapObjName,
attribute));
return heapMemoryUsage;
}
private OperatingSystemMXBean getOSInfo(MBeanServerConnection mBeanSConnection) throws Exception{
ObjectName osObjectName=null;
OperatingSystemMXBean osMBeanProxy = null;
osObjectName = new ObjectName(CommonConstants.OPERATIONSYSYTEM_OBJECT_NAME);
osMBeanProxy = JMX.newMBeanProxy(mBeanSConnection, osObjectName, OperatingSystemMXBean.class);
return osMBeanProxy;
}
private Map<String, String> getJstatFields() throws Exception {
Map<String, String> jstatFields = new HashMap<String, String>();
jstatFields = getGCInfo();
// TODO log error
return jstatFields;
}
private Map<String, String> getGCInfo() throws Exception{
// linux
// String[] cmd = new String[] { CommonConstants.BASH_CMD,
// CommonConstants.C_CMD, CommonConstants.JSTAT_COMAND };
String cmd = "jstat -gcutil 6764";
Runtime run = Runtime.getRuntime();
BufferedInputStream in = null;
BufferedReader inBr = null;
Process p = run.exec(cmd);
in = new BufferedInputStream(p.getInputStream());
inBr = new BufferedReader(new InputStreamReader(in));
String lineStr = null;
String[] fieldsName = null;
String[] fieldsValue = null;
while ((lineStr = inBr.readLine()) != null) {
lineStr = lineStr.trim();
if (lineStr.startsWith("S")) {
fieldsName = new String(lineStr.getBytes()).replaceAll("\\s+", "|").split("\\|");
} else {
fieldsValue = new String(lineStr.getBytes()).replaceAll("\\s+", "|").split("\\|");
}
}
if (p.waitFor() != 0) {
if (p.exitValue() == 1)
System.err.println("fail ");
}
Map<String, String> fields = null;
if (fieldsName.length == fieldsValue.length) {
fields = new HashMap<String, String>();
for (int i = 0; i < fieldsName.length; i++) {
fields.put(fieldsName[i], fieldsValue[i]);
}
}
inBr.close();
in.close();
return fields;
}
private boolean isNotNull(MBeanServerConnection mBeanSConnection,MemoryUsage heapMemoryUsage,MemoryUsage nonHeapMemoryUsage,OperatingSystemMXBean osInfo,Map<String,String> gcInfo){
return (null != heapMemoryUsage)&&(null != nonHeapMemoryUsage) && (null != mBeanSConnection) && (null != osInfo) && (null!=gcInfo);
}
}
Every private method I throw exception instead of trying catch immediately. Finally, I catch all exception on the main method.
每个私有方法我抛出异常而不是立即尝试捕获。最后,我在main方法上捕获了所有异常。
When should I try catch or throws? Please someone help ! Am i right?
我该什么时候尝试捕捉或抛出?请有人帮忙!我对吗?
1 个解决方案
#1
Though question seems to be very broad, but you need understanding on Java Exception framework + bit of design patterns
虽然问题似乎很广泛,但您需要了解Java Exception框架+一些设计模式
1.) If you are exposing some public methods in a service, it is always better to catch exception
1.)如果您在服务中公开一些公共方法,最好捕获异常
Log Exception -> Return proper error code/message
2.) throwing exception means everyone who is calling that method has to handle the exception on its own.
2.)抛出异常意味着每个调用该方法的人都必须自己处理异常。
3.) If there are any changes to the internal implementation of the method, then you might end up throwing a different exception.
3.)如果方法的内部实现有任何更改,那么您可能最终会抛出一个不同的异常。
4.) Also throwing the superclass Exception
, again looses the focus from the precision.
4.)同时抛出超类Exception,再次失去精度的焦点。
#1
Though question seems to be very broad, but you need understanding on Java Exception framework + bit of design patterns
虽然问题似乎很广泛,但您需要了解Java Exception框架+一些设计模式
1.) If you are exposing some public methods in a service, it is always better to catch exception
1.)如果您在服务中公开一些公共方法,最好捕获异常
Log Exception -> Return proper error code/message
2.) throwing exception means everyone who is calling that method has to handle the exception on its own.
2.)抛出异常意味着每个调用该方法的人都必须自己处理异常。
3.) If there are any changes to the internal implementation of the method, then you might end up throwing a different exception.
3.)如果方法的内部实现有任何更改,那么您可能最终会抛出一个不同的异常。
4.) Also throwing the superclass Exception
, again looses the focus from the precision.
4.)同时抛出超类Exception,再次失去精度的焦点。