5

我正在使用 Java 的 codahale Metrics API。

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

在性能测试期间,我们通过 JMX 连接到我们的系统以收集统计信息,例如平均延迟、75th Percentile 延迟等。

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

任何帮助,将不胜感激。

4

1 回答 1

2

我不知道现有的方法,但您可以将resetTimers() 功能扩展并添加到MetricRegistry。您必须从 codahale 指标 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);
        }
    }
}
于 2015-05-06T13:04:09.457 回答