本文整理匯總了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));
}
示例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();
}
示例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();
}
}
示例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);
}
示例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);
}
示例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);
}
示例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));
}
示例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.
}
示例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");
}
}
});
}
示例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());
}
示例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));
}
示例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);
}
示例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();
}
}
示例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());
}
示例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);
}