Java 모니터링 요청

2968 단어
감시 대상

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();
        }       
    }
}

좋은 웹페이지 즐겨찾기