com.alibaba.tmq.common.monitor.timer.MethodCountTimer Maven / Gradle / Ivy
package com.alibaba.tmq.common.monitor.timer;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import com.alibaba.tmq.common.domain.remoting.Pair;
import com.alibaba.tmq.common.monitor.callback.Display;
import com.alibaba.tmq.common.util.LoggerUtil;
/**
* 方法统计定时器
* @author tianyao.myc
*
*/
public class MethodCountTimer extends TimerTask {
private final Log logger;
//展现信息列表
private final List displayList;
private final ConcurrentHashMap> methodCountTable;
public MethodCountTimer(Log logger, List displayList, ConcurrentHashMap> methodCountTable) {
this.logger = logger;
this.displayList = displayList;
this.methodCountTable = methodCountTable;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void run() {
StringBuilder counterLog = new StringBuilder("display start\n\n");
if(this.displayList != null && this.displayList.size() > 0) {
for(Display display : this.displayList) {
counterLog.append(" " + display.content() + "\n");
}
counterLog.append("\n");
}
List header = new ArrayList();
String key = "method name";header.add("invoke per second");header.add("response time (ms)");
Map> body = new HashMap>();
Iterator iterator = methodCountTable.entrySet().iterator();
while (iterator.hasNext()) {
try {
Map.Entry entry = (Map.Entry) iterator.next();
String methodName = (String)entry.getKey();
Pair countPair = (Pair)entry.getValue();
AtomicLong counter = countPair.getObject1();
AtomicLong totalTime = countPair.getObject2();
List itemList = new ArrayList();
itemList.add(counter.toString());
itemList.add(String.valueOf(0L == counter.get() ? 0L : totalTime.get() / counter.get()));
body.put(methodName, itemList);
counter.set(0L);//计数器清零
totalTime.set(0L);//耗时清零
} catch (Throwable e) {
logger.error("[MethodCountTimer]: count error", e);
}
}
counterLog.append(LoggerUtil.displayTable(key, header, body) + "\n\n\n");
logger.info(counterLog.toString());
}
}