Java 监控请求

监控对象


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();
}
}
}
上一篇:Redis数据过期和淘汰策略详解(转)


下一篇:51nod1174(RMQ)