缓存中的一个共享统计对象:
public class MsgContent {
/**方法名称*/
private String methodName;
/**消息次数统计*/
private AtomicInteger count;
/**错误信息列表*/
private List<String> errMsg;
/**错误信息列表,调用本方法,统计值 +1,线程并发安全*/
public void addCount() {
count.incrementAndGet();
}
/**同步方法实现线程安全*/
public synchronized void addMsg(String msg) {
if(this.errMsg.size() < DingTalkConfigure.CACHE_ERR_MSG_COUNT){
errMsg.add(msg);
}
}
public MsgContent(String methodName) {
this.methodName = methodName;
this.count = new AtomicInteger(0);
this.errMsg = new LinkedList<>();
}
}
使用:
String methodName = "";
String key = getKey(bizName, methodName, appName);
Map<String, msgContert> cacheMap = DingTalkConfigure.getCurrentHashMap();
long currentTimeMillis = System.currentTimeMillis();
//ConcurrentHashMap 的安全API,并发场景下通过key获取元素,获取不到则返回新对象。
MsgContent dingTalkMsgContent = cacheMap.computeIfAbsent(key,
k -> new MsgContent( methodName));
//值统计有效期范围内的数据并累加(线程安全)
dingTalkMsgContent.addCount();
dingTalkMsgContent.addMsg(errMsg);