監控對象
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/**
* 監控對象
*
* @author solq
* */
public class Monitor {
/** 每分鐘記錄 */
private ConcurrentHashMap<Long, Integer> record = new ConcurrentHashMap<>();
/** 記錄間隔 */
private long recordInterval;
/** 清理間隔 */
private long cleanInterval;
/** 記錄名稱 */
private String name;
/** 最後清理時間 */
private long lastClean = System.currentTimeMillis();
public static Monitor valueOf(String name, long recordInterval,
long cleanInterval) {
Monitor result = new Monitor();
result.name = name;
result.recordInterval = recordInterval;
result.cleanInterval = cleanInterval;
return result;
}
public void record() {
final long start = System.currentTimeMillis();
// 去掉除數 達到取上一時間點效果
final long key = (start / recordInterval) * recordInterval;
if (Math.abs((start- lastClean)) > cleanInterval) {
synchronized (this) {
if (Math.abs((start- lastClean))> cleanInterval) {
printlnAndClean();
}
}
}
record(key);
}
void record(Long key) {
while (true) {
Integer value = record.get(key);
if (value == null) {
if (record.putIfAbsent(key, 1) == null) {
break;
}
} else {
if (record.replace(key, value, value + 1)) {
break;
}
}
}
}
/**
* 打印並清理記錄
* */
private void printlnAndClean() {
lastClean = System.currentTimeMillis();
Map<Long, Integer> data = new HashMap<>(record);
record.clear();
for (Entry<Long, Integer> entry : data.entrySet()) {
System.err.println(name
+ " Monitor : "
+ DateUtils.date2String(new Date(entry.getKey()),
DateUtils.PATTERN_DATE_TIME) + " : "
+ entry.getValue());
}
}
}
監控使用包裝
/**
* 請求監控工具
*
* @author solq
* */
public abstract class RequestMonitorUtil {
private static Monitor commandMonitor = Monitor.valueOf("命令代理", 60 * 1000,
60 * 60 * 1000);
private static Monitor sqlMonitor = Monitor.valueOf("sql代理", 60 * 1000,
60 * 60 * 1000);
public static void recordSql() {
try {
commandMonitor.record();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void recordCommand() {
try {
sqlMonitor.record();
} catch (Exception e) {
e.printStackTrace();
}
}
}