当前位置: 首页>>代码示例>>Java>>正文


Java Counter类代码示例

本文整理汇总了Java中com.codahale.metrics.Counter的典型用法代码示例。如果您正苦于以下问题:Java Counter类的具体用法?Java Counter怎么用?Java Counter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Counter类属于com.codahale.metrics包,在下文中一共展示了Counter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testMetricEncode

import com.codahale.metrics.Counter; //导入依赖的package包/类
/**
 * Tests encoding of a Metric object.
 */
@Test
public void testMetricEncode() {
    Counter counter = new Counter();
    Meter meter = new Meter();
    Timer timer = new Timer();

    counter.inc();
    meter.mark();
    timer.update(1, TimeUnit.MILLISECONDS);

    ObjectNode counterJson = metricCodec.encode(counter, context);
    assertThat(counterJson.get("counter"), matchesMetric(counter));

    ObjectNode meterJson = metricCodec.encode(meter, context);
    assertThat(meterJson.get("meter"), matchesMetric(meter));

    ObjectNode timerJson = metricCodec.encode(timer, context);
    assertThat(timerJson.get("timer"), matchesMetric(timer));
}
 
开发者ID:shlee89,项目名称:athena,代码行数:23,代码来源:MetricCodecTest.java

示例2: AttributeQueryRequestRunnable

import com.codahale.metrics.Counter; //导入依赖的package包/类
public AttributeQueryRequestRunnable(
        SessionId sessionId,
        AttributeQueryContainerDto attributeQueryContainerDto,
        ExecuteAttributeQueryRequest executeAttributeQueryRequest,
        @MatchingServiceRequestExecutorBacklog Counter counter,
        TimeoutEvaluator timeoutEvaluator,
        HubMatchingServiceResponseReceiverProxy hubMatchingServiceResponseReceiverProxy,
        ServiceInfoConfiguration serviceInfo,
        EventSinkProxy eventSinkProxy) {
    this.counter = counter;
    this.sessionId = sessionId;
    this.attributeQueryContainerDto = attributeQueryContainerDto;
    this.executeAttributeQueryRequest = executeAttributeQueryRequest;
    this.timeoutEvaluator = timeoutEvaluator;
    this.hubMatchingServiceResponseReceiverProxy = hubMatchingServiceResponseReceiverProxy;
    this.serviceInfo = serviceInfo;
    this.eventSinkProxy = eventSinkProxy;
    this.counter.inc();
}
 
开发者ID:alphagov,项目名称:verify-hub,代码行数:20,代码来源:AttributeQueryRequestRunnable.java

示例3: invoke

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {

    EnableMetricCounter annotation = methodInvocation.getThis().getClass().getAnnotation(EnableMetricCounter.class);

    String name = StringUtils.isBlank(annotation.value())
            ? methodInvocation.getThis().getClass().getName() + "." + methodInvocation.getMethod().getName()
            : annotation.value();

    Counter counter = Jboot.me().getMetric().counter(name);
    try {
        counter.inc();
        return methodInvocation.proceed();
    } finally {
        counter.dec();
    }

}
 
开发者ID:yangfuhai,项目名称:jboot,代码行数:19,代码来源:JbootMetricConterAopInterceptor.java

示例4: setup

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Before
public void setup() throws RpcCallException {
    handlerDictionary = new MethodHandlerDictionary();
    handlerDictionary.put("a", null);
    ServiceMethodHandlerUnderTest mockHandlerThrowsRpcCallEx = new ServiceMethodHandlerUnderTest();

    handlerDictionary.put("jsonRpcWithException", mockHandlerThrowsRpcCallEx);

    metricRegistry = mock(MetricRegistry.class);
    when(metricRegistry.counter(anyString())).thenReturn(mock(Counter.class));
    when(metricRegistry.timer(anyString())).thenReturn(mock(Timer.class));

    handlerMetrics = mock(RpcHandlerMetrics.class);
    when(handlerMetrics.getMethodTimer(any(), any(), any())).thenReturn(mock(GoTimer.class));

    servlet = new JsonHandler(handlerDictionary, metricRegistry, handlerMetrics, new ServiceProperties(), null);
}
 
开发者ID:Sixt,项目名称:ja-micro,代码行数:18,代码来源:JsonHandlerTest.java

示例5: report

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Override
public void report(final SortedMap<String, Gauge> gauges,
                   final SortedMap<String, Counter> counters,
                   final SortedMap<String, Histogram> histograms,
                   final SortedMap<String, Meter> meters,
                   final SortedMap<String, Timer> timers) {
  final long timestamp = clock.instant().toEpochMilli();

  final ImmutableList<InfluxDbMeasurement> influxDbMeasurements = ImmutableList.<InfluxDbMeasurement>builder()
    .addAll(transformer.fromGauges(gauges, timestamp))
    .addAll(transformer.fromCounters(counters, timestamp))
    .addAll(transformer.fromHistograms(histograms, timestamp))
    .addAll(transformer.fromMeters(meters, timestamp))
    .addAll(transformer.fromTimers(timers, timestamp))
    .build();

  sender.send(influxDbMeasurements);
}
 
开发者ID:kickstarter,项目名称:dropwizard-influxdb-reporter,代码行数:19,代码来源:InfluxDbMeasurementReporter.java

示例6: testFromCounters_Grouped

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Test
public void testFromCounters_Grouped() {
  final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
  final DropwizardTransformer transformer = transformerWithParser(parser, true);

  final List<Counter> counters = ImmutableList.of(new Counter(), new Counter());
  counters.get(0).inc(15L);
  counters.get(1).inc(6L);

  final Map<String, Counter> cMap = ImmutableMap.of(
    "some.stuff.queued", counters.get(0),
    "some.stuff.processed", counters.get(1)
  );

  when(parser.parse("some.stuff")).thenReturn(
    DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
  );

  final List<InfluxDbMeasurement> expected = ImmutableList.of(
    InfluxDbMeasurement.create("some.stuff", ALL_TAGS, ImmutableMap.of("queued", "15i", "processed", "6i"), 90210L)
  );

  final List<InfluxDbMeasurement> measurements = transformer.fromCounters(cMap, 90210L);
  assertEquals("should group counters by tags and prefix", expected, measurements);
}
 
开发者ID:kickstarter,项目名称:dropwizard-influxdb-reporter,代码行数:26,代码来源:DropwizardTransformerTest.java

示例7: testMetricSetAnnotations

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Test
public void testMetricSetAnnotations() {
    Map<String, Metric> metrics = new TestLambdaMetricSet().getMetrics();

    // Prove that the defaults fall back to the classname as namespace, and field name as metric name.
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/fooCounter"),
            instanceOf(Counter.class));

    // Prove we can override the name via the annotation
    assertThat(metrics.get("io.symphonia.lambda.metrics.LambdaMetricSetTest.TestLambdaMetricSet/myBarCounter"),
            instanceOf(Counter.class));

    // Prove we can override the namespace via the annotation
    assertThat(metrics.get("test.namespace/bazCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace and name via the annotation
    assertThat(metrics.get("test.namespace/myBingCounter"), instanceOf(Counter.class));

    // Prove we can override the namespace via a class-level annotation
    assertThat(new NamespaceTestLambdaMetricSet().getMetrics().get("test.namespace/fooCounter"),
            instanceOf(Counter.class));
}
 
开发者ID:symphoniacloud,项目名称:lambda-monitoring,代码行数:23,代码来源:LambdaMetricSetTest.java

示例8: reportCounter

import com.codahale.metrics.Counter; //导入依赖的package包/类
/**
 * A counter is just a gauge for an AtomicLong instance. You can increment or decrement its
 * value. We want a more efficient way of measuring the pending job in a queue
 */
private static void reportCounter() {
    // Create or fetch (if it is already created) the metric.
    final Counter counter = registry.counter(APP_PREFIX.tagged("what", "job-count"));

    // Somewhere in your code where you are adding new jobs to the queue you increment the
    // counter as well
    counter.inc();

    // Oh look! Another job!
    counter.inc();

    // Somewhere in your code the job is going to be removed from the queue you decrement the
    // counter
    counter.dec();

    // That's it! The rest will be automatically done inside semantic metrics library. The
    // reported measurements will be kept in the registry.
    // Every time the reporter wants to report, the current value of the counter will be read
    // and
    // a datapoint will be created and reported.
}
 
开发者ID:spotify,项目名称:semantic-metrics,代码行数:26,代码来源:MetricTypesExample.java

示例9: initDiscordHealthChecks

import com.codahale.metrics.Counter; //导入依赖的package包/类
private void initDiscordHealthChecks() {
    healthCheckRegistry.register(MetricNames.HEALTH_DISCORD_WS, new HealthCheck() {
        @Override
        protected Result check() throws Exception {
            Counter restartCounter = metricRegistry.counter(MetricNames.DISCORD_WS_RESTARTS);
            Optional<Incident> incident = incidentService.getLastIncidentFromGroup(IncidentService.DISCORD_RESTART);
            ZonedDateTime time = incident.isPresent() ? incident.get().getCreatedDate() : null;
            String reason = incident.isPresent() ? incident.get().getName() : null;
            long restarts = restartCounter.getCount();
            if (restarts > 0) {
                return Result.unhealthy(String.format("%d restart%s, last one on %s (%s)",
                    restarts, restarts == 1 ? "" : "s", time, reason));
            } else {
                return Result.healthy("OK");
            }
        }
    });
}
 
开发者ID:quanticc,项目名称:ugc-bot-redux,代码行数:19,代码来源:MetricsService.java

示例10: testCounterReporting

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Test public void testCounterReporting() {
  final Counter counter = new Counter();

  TreeMap<String,Counter> counters = new TreeMap<>();
  counters.put("my_counter", counter);
  // Add the metrics objects to the internal "queues" by hand
  metrics2Reporter.setDropwizardCounters(counters);

  // Set some values
  counter.inc(5L);

  MetricsCollector collector = mock(MetricsCollector.class);
  MetricsRecordBuilder recordBuilder = mock(MetricsRecordBuilder.class);

  Mockito.when(collector.addRecord(recordName)).thenReturn(recordBuilder);

  metrics2Reporter.getMetrics(collector, true);

  verify(recordBuilder).addCounter(Interns.info("my_counter", ""), 5L);
  verifyRecordBuilderUnits(recordBuilder);

  // Should not be the same instance we gave before. Our map should have gotten swapped out.
  assertTrue("Should not be the same map instance after collection",
      counters != metrics2Reporter.getDropwizardCounters());
}
 
开发者ID:joshelser,项目名称:dropwizard-hadoop-metrics2,代码行数:26,代码来源:HadoopMetrics2ReporterTest.java

示例11: reportsWithCallback

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Test
public void reportsWithCallback() throws Exception {
  List<String> dynamicTags = new ArrayList<String>();
  dynamicTags.add("status:active");
  dynamicTags.add("speed:29");

  when(callback.getTags()).thenReturn(dynamicTags);

  final Counter counter = mock(Counter.class);
  when(counter.getCount()).thenReturn(100L);

  reporterWithCallback.report(this.<Gauge>map(),
          this.<Counter>map("counter", counter),
          this.<Histogram>map(),
          this.<Meter>map(),
          this.<Timer>map());

  verify(request).addGauge(new CirconusGauge("counter", 100L, timestamp, HOST, dynamicTags));
}
 
开发者ID:circonus-labs,项目名称:metrics-circonus,代码行数:20,代码来源:CirconusReporterTest.java

示例12: shouldReportCounter

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Test
public void shouldReportCounter() throws IOException {
    String metricName = randomName();
    HawkularReporter reporter = HawkularReporter.builder(registry, defaultTenant)
            .basicAuth(USERNAME, PASSWORD)
            .build();

    final Counter counter = registry.counter(metricName);
    counter.inc(5);
    reporter.report();

    HawkularHttpResponse response = defaultClient.readMetric("counters", metricName);

    assertThat(response.getResponseCode()).isEqualTo(200);
    JSONArray result = new JSONArray(response.getContent());
    assertThat(result).extracting(intExtractor).containsExactly(5);

    counter.inc(8);
    reporter.report();

    response = defaultClient.readMetric("counters", metricName);

    assertThat(response.getResponseCode()).isEqualTo(200);
    result = new JSONArray(response.getContent());
    assertThat(result).extracting(intExtractor).containsExactly(13, 5);
}
 
开发者ID:hawkular,项目名称:hawkular-dropwizard-reporter,代码行数:27,代码来源:HawkularReporterITest.java

示例13: doProcess

import com.codahale.metrics.Counter; //导入依赖的package包/类
@Override
protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception {
    Message in = exchange.getIn();
    Counter counter = registry.counter(metricsName);
    Long increment = endpoint.getIncrement();
    Long decrement = endpoint.getDecrement();
    Long finalIncrement = getLongHeader(in, HEADER_COUNTER_INCREMENT, increment);
    Long finalDecrement = getLongHeader(in, HEADER_COUNTER_DECREMENT, decrement);
    if (finalIncrement != null) {
        counter.inc(finalIncrement);
    } else if (finalDecrement != null) {
        counter.dec(finalDecrement);
    } else {
        counter.inc();
    }
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:17,代码来源:CounterProducer.java

示例14: HBaseApplier

import com.codahale.metrics.Counter; //导入依赖的package包/类
/**
 * HBaseApplier constructor.
 * @param config config
 * @param mainProgressIndicator mainProgressIndicator
 * @param validationService validationService
 */
public HBaseApplier(
    com.booking.replication.Configuration config,
    Counter mainProgressIndicator,
    ValidationService validationService
) {
    configuration = config;

    hbaseApplierWriter =
        new HBaseApplierWriter(
                POOL_SIZE,
                configuration,
                mainProgressIndicator,
                validationService
        );

    hbaseSchemaManager = new HBaseSchemaManager(
            configuration.getHBaseQuorum(), configuration.isDryRunMode());
}
 
开发者ID:mysql-time-machine,项目名称:replicator,代码行数:25,代码来源:HBaseApplier.java

示例15: getNamedCounter_with_varargs_dimensions_creates_dimensioned_counter_using_sfx_mechanisms

import com.codahale.metrics.Counter; //导入依赖的package包/类
@DataProvider(value = {
    "null",
    "0",
    "1",
    "2"
}, splitBy = "\\|")
@Test
public void getNamedCounter_with_varargs_dimensions_creates_dimensioned_counter_using_sfx_mechanisms(
    Integer numDimensions
) {
    // given
    String counterName = UUID.randomUUID().toString();
    Pair<String, String>[] varargDims = generateVarargDimensions(numDimensions);
    List<Pair<String, String>> dimsAsList = (varargDims == null) ? null : Arrays.asList(varargDims);

    // when
    Counter result = sfxImpl.getNamedCounter(counterName, varargDims);

    // then
    verifyMetricCreation(MetricBuilder.COUNTERS, counterTaggerMock, counterName, dimsAsList, counterMock, result);
}
 
开发者ID:Nike-Inc,项目名称:riposte,代码行数:22,代码来源:SignalFxAwareCodahaleMetricsCollectorTest.java


注:本文中的com.codahale.metrics.Counter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。