如何清除Java codahale Metrics Timers的历史统计数据

我使用codahale Metrics API for
Java.

我们在整个系统中使用计时器来收集延迟.

在性能测试期间,我们通过JMX连接到我们的系统以收集统计数据,例如平均延迟,第75百分位延迟等.

问题是,如果没有删除所有Metrics对象并重新创建它们(看起来好像需要进行大量重构),是否有办法清除历史数据,这样当我们开始新的测试时,我们不需要重新启动出系统?

任何帮助,将不胜感激.

最佳答案 我不知道现有的方法,但你可以扩展并添加resetTimers()功能到MetricRegistry.

你必须从codahale metrics repo实现你自己的Reservoir或分支.

ResettableUniformReservoir是从UniformReservoir复制的.

默认的Reservoir实现是ExponentiallyDecayingReservoir,但是需要复制的代码更多:)

public class MyRegistry extends MetricRegistry {

    private final ConcurrentMap<String, ResettableUniformReservoir> reservoirs = new ConcurrentHashMap<>();

    @Override
    public Timer timer(String name) {
         ResettableUniformReservoir reservoir = new ResettableUniformReservoir();
         reservoirs.put(name, reservoir);
         return super.register(name, new Timer(reservoir));
    }

    public void resetTimers() {
        for (ResettableUniformReservoir reservoir : reservoirs.values()) {
            reservoir.reset();
        }
    }


    static class ResettableUniformReservoir implements Reservoir {

        private static final int DEFAULT_SIZE = 1028;
        private static final int BITS_PER_LONG = 63;

        private final AtomicLong count = new AtomicLong();
        private volatile AtomicLongArray values = new AtomicLongArray(DEFAULT_SIZE);

        @Override
        public int size() {
            final long c = count.get();
            if (c > values.length()) {
                return values.length();
            }
            return (int) c;
        }

        @Override
        public void update(long value) {
            final long c = count.incrementAndGet();
            if (c <= values.length()) {
                values.set((int) c - 1, value);
            } else {
                final long r = nextLong(c);
                if (r < values.length()) {
                    values.set((int) r, value);
                }
            }
        }

        private static long nextLong(long n) {
            long bits, val;
            do {
                bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG));
                val = bits % n;
            } while (bits - val + (n - 1) < 0L);
            return val;
        }

        @Override
        public Snapshot getSnapshot() {
            final int s = size();
            final List<Long> copy = new ArrayList<Long>(s);
            for (int i = 0; i < s; i++) {
                copy.add(values.get(i));
            }
            return new UniformSnapshot(copy);
        }

        public void reset() {
            count.set(0);
            values = new AtomicLongArray(DEFAULT_SIZE);
        }
    }
}
点赞