Codahale 指标计数器重置并每天计数

Codahale metrics counter reset and count everyday

使用 Codahale 指标可以计算过去 24 小时(今天)。

生成如下报告:

请求计数:

lastSec   lastMin    lastHour    today
=======================================
1           5           22        45   

响应计数:

lastSec   lastMin    lastHour    today
=======================================
1           5           22        45   

Meter methods 获取最后一秒、分钟、十五的费率。但是 如何计算最后一小时和今天的计数?

下面试过:

public class ReportMetrics {

    static final MetricRegistry metrics = new MetricRegistry();
    static final Counter aReqCount = ReportMetrics.metrics.counter(name(AProcessor.class, "a-req-count"));
    static final Counter aResCount = ReportMetrics.metrics.counter(name(AProcessor.class, "a-res-count"));
    
    private static final AProcessor aProcessor = new AProcessor();
    
    public static void main(String[] args) {
        startReport();
        
        for(int i=0; i<=5; i++){
            //add
            aProcessor.addJob();
            wait5Seconds();         
            
            //take
            arProcessor.takeJob();
            wait5Seconds();         
        }
        
    }
    
    static void startReport() {
          ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
              .convertRatesTo(TimeUnit.SECONDS)
              .convertDurationsTo(TimeUnit.MILLISECONDS)
              .build();
          reporter.start(1, TimeUnit.SECONDS);
      }
    
    static void wait5Seconds() {
          try {
              Thread.sleep(5*1000);
          }
          catch(InterruptedException e) {}
      }
    
    public long requestCount(){
        ReportMetrics.metrics.aReqCount.getCount();
    }
    
    public long responseCount(){
        ReportMetrics.metrics.aResCount.getCount();
    }
    
    public long pendingRequestCount(){
        return requestCount() - responseCount();
    }   
    
}

class AProcessor {
    
    public void addJob(){
        ReportMetrics.metrics.aReqCount.inc();
    }

    public Object takeJob(){
        ReportMetrics.metrics.aResCount.inc();
    }
}

为使用 counter.inc 报告的计数器计算每个任意时间间隔的计数(总计):

hitcount(perSecond(AProcessor.a-req-count.count), '1hour')

hitcount(perSecond(AProcessor.a-res-count.count), '1day')

Afaik 它在里面做了所有的黑魔法。包括但不限于summarize(scaleToSeconds(nonNegativeDerivative(your.count),1), '1day') 并且还应该根据落入所选聚合间隔的碳的保留期(一个或多个)进行缩放。