下面列出了怎么用com.codahale.metrics.SharedMetricRegistries的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void callGaugesAfterSetterCalls() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Gauges are not registered correctly", registry.getGauges().keySet(), is(equalTo(absoluteMetricNames())));
long value = Math.round(Math.random() * Long.MAX_VALUE);
// Call the setter methods
instance.setPublicGauge(value);
instance.setPackagePrivateGauge(value);
instance.setProtectedGauge(value);
method("setPrivateGauge").withParameterTypes(long.class).in(instance).invoke(value);
// And assert the gauges are up-to-date
assertThat("Gauge values are incorrect", registry.getGauges().values(), everyItem(Matchers.<Gauge>hasProperty("value", equalTo(value))));
}
/**
* Remove a named registry.
*
* @param registry name of the registry to remove
*/
public void removeRegistry(String registry) {
// close any reporters for this registry first
closeReporters(registry, null);
// make sure we use a name with prefix
registry = enforcePrefix(registry);
if (isSharedRegistry(registry)) {
SharedMetricRegistries.remove(registry);
} else {
swapLock.lock();
try {
registries.remove(registry);
} finally {
swapLock.unlock();
}
}
}
@Test
public void testMetricChange() throws Exception {
Metrics metrics = new Metrics();
DropwizardReporter reporter = new DropwizardReporter();
reporter.configure(new HashMap<String, Object>());
metrics.addReporter(reporter);
Sensor sensor = metrics.sensor("kafka.requests");
sensor.add(new MetricName("pack.bean1.avg", "grp1"), new Avg());
Map<String, Gauge> gauges = SharedMetricRegistries.getOrCreate("default").getGauges();
String expectedName = "org.apache.kafka.common.metrics.grp1.pack.bean1.avg";
Assert.assertEquals(1, gauges.size());
Assert.assertEquals(expectedName, gauges.keySet().toArray()[0]);
sensor.record(2.1);
sensor.record(2.2);
sensor.record(2.6);
Assert.assertEquals(2.3, (Double)gauges.get(expectedName).getValue(), 0.001);
}
@Inject
public EventSchedulerService(EventSchedulerDao eventSchedulerDao, EventSchedulerRegistry eventSchedulerRegistry,
@Named("eventScheduler.batchRead.intervalms") Integer batchReadInterval,
@Named("eventScheduler.batchRead.batchSize") Integer batchSize,
ObjectMapper objectMapper) {
this.eventSchedulerDao = eventSchedulerDao;
this.eventSchedulerRegistry = eventSchedulerRegistry;
this.batchReadInterval = batchReadInterval;
this.batchSize = batchSize;
this.objectMapper = objectMapper;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
// remove the task from scheduler on cancel
executor.setRemoveOnCancelPolicy(true);
scheduledExecutorService =
new InstrumentedScheduledExecutorService(Executors.unconfigurableScheduledExecutorService(executor),
SharedMetricRegistries.getOrCreate(METRIC_REGISTRY_NAME), scheduledExectorSvcName);
}
@Test
public void addMetricsCapability() {
final MetricRegistry registry = SharedMetricRegistries.getOrCreate("unit_test");
final SimpleSource source = Feign.builder()
.client(new MockClient()
.ok(HttpMethod.GET, "/get", "1234567890abcde"))
.addCapability(new Metrics4Capability(registry))
.target(new MockTarget<>(Metrics4CapabilityTest.SimpleSource.class));
source.get("0x3456789");
assertThat(registry.getMetrics(), aMapWithSize(6));
registry.getMetrics().keySet().forEach(metricName -> assertThat(
"Expect all metric names to include client name:" + metricName,
metricName,
containsString("feign.metrics4.Metrics4CapabilityTest$SimpleSource")));
registry.getMetrics().keySet().forEach(metricName -> assertThat(
"Expect all metric names to include method name:" + metricName,
metricName,
containsString("get")));
}
@Override
public MetricRegistry resolveMetricRegistry(String registry) {
Matcher matcher = EL_PATTERN.matcher(registry);
if (matcher.matches()) {
Object evaluation = processor.eval(matcher.group(1));
if (evaluation instanceof String)
return SharedMetricRegistries.getOrCreate((String) evaluation);
else if (evaluation instanceof MetricRegistry)
return (MetricRegistry) evaluation;
else
throw new IllegalStateException("Unable to resolve metrics registry from expression [" + registry + "]");
} else if (!matcher.find()) {
return SharedMetricRegistries.getOrCreate(registry);
} else {
return SharedMetricRegistries.getOrCreate(evaluateCompositeExpression(matcher));
}
}
/**
* Constructor
*
* @param client Riak client
* @param idGenerator ID Generator
* @param cursors Cursor data store
* @param ruleStore Rule data store
* @param timeout Riak server-side timeout
* @param requestTimeout Riak client-side timeout
*/
public NotificationStore(
final RiakClient client,
final IdGenerator idGenerator,
final CursorStore cursors,
final RuleStore ruleStore,
final Duration timeout,
final Duration requestTimeout) {
final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
this.fetchTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "fetch"));
this.updateTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "store"));
this.deleteTimer = registry.timer(MetricRegistry.name(NotificationStore.class, "delete"));
this.client = Objects.requireNonNull(client, "client == null");
this.idGenerator = Objects.requireNonNull(idGenerator, "idGenerator == null");
this.cursors = Objects.requireNonNull(cursors, "cursors == null");
this.ruleStore = Objects.requireNonNull(ruleStore, "ruleStore == null");
this.timeout =
Optional.ofNullable(timeout)
.map(t -> Math.toIntExact(t.toMilliseconds()))
.orElse(DEFAULT_TIMEOUT_MS);
this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");
}
/**
* Constructor
*
* @param client Riak client
* @param timeout Riak server-side timeout
* @param requestTimeout Riak client-side timeout
*/
public CursorStore(
final RiakClient client, final Duration timeout, final Duration requestTimeout) {
final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
this.fetchTimer = registry.timer(MetricRegistry.name(CursorStore.class, "fetch"));
this.storeTimer = registry.timer(MetricRegistry.name(CursorStore.class, "store"));
this.deleteTimer = registry.timer(MetricRegistry.name(CursorStore.class, "delete"));
this.client = Objects.requireNonNull(client, "client == null");
this.timeout =
Optional.ofNullable(timeout)
.map(t -> Math.toIntExact(t.toMilliseconds()))
.orElse(DEFAULT_TIMEOUT_MS);
this.requestTimeout = Objects.requireNonNull(requestTimeout, "requestTimeout == null");
}
@Test
public void testConnectionLife() throws SQLException {
// Act
Connection connection = DriverManager.getConnection(URL + ";metrics_registry=life", H2DbUtil.USERNAME, H2DbUtil.PASSWORD);
Statement statement = connection.createStatement();
H2DbUtil.close(statement, connection);
// Assert
assertNotNull(connection);
assertTrue(Proxy.isProxyClass(connection.getClass()));
MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate("life");
Timer lifeTimer = metricRegistry.timer("java.sql.Connection");
assertNotNull(lifeTimer);
assertThat(lifeTimer.getCount(), equalTo(1L));
Timer getTimer = metricRegistry.timer("java.sql.Connection.get");
assertNotNull(getTimer);
assertThat(getTimer.getCount(), equalTo(1L));
}
@Test
public void callMetricsStaticMethodsOnce() {
// Call the monitored method and assert all the metrics have been created and marked
MultipleMetricsStaticMethod.metricsMethod();
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Metrics are not registered correctly", registry.getMetrics().keySet(), is(equalTo(absoluteMetricNames())));
// Make sure that the metrics have been called
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("exception")).getCount(), is(equalTo(0L)));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName("meter")).getCount(), is(equalTo(1L)));
assertThat("Timer count is incorrect", registry.getTimers().get(absoluteMetricName("timer")).getCount(), is(equalTo(1L)));
assertThat("Gauge value is incorrect", registry.getGauges().get(absoluteMetricName("gauge")).getValue(), hasToString((equalTo("value"))));
}
@Test
public void callExceptionMeteredMethodsOnceWithoutThrowing() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
@Override
public void run() {
}
};
// Call the metered methods and assert they haven't been marked
instance.illegalArgumentExceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
instance.exceptionMeteredMethod(runnableThatDoesNoThrowExceptions);
assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
}
@Test
public void callExceptionMeteredMethodOnceWithThrowingExpectedException() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
final RuntimeException exception = new IllegalArgumentException("message");
Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
@Override
public void run() {
throw exception;
}
};
// Call the metered method and assert it's been marked and that the original exception has been rethrown
try {
instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalArgumentException);
} catch (RuntimeException cause) {
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(1L)));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(0L)));
assertSame("Exception thrown is incorrect", cause, exception);
return;
}
fail("No exception has been re-thrown!");
}
@Test
public void callExceptionMeteredMethodOnceWithThrowingNonExpectedException() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
final RuntimeException exception = new IllegalStateException("message");
Runnable runnableThatThrowsIllegalStateException = new Runnable() {
@Override
public void run() {
throw exception;
}
};
// Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
try {
instance.illegalArgumentExceptionMeteredMethod(runnableThatThrowsIllegalStateException);
} catch (RuntimeException cause) {
assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
assertSame("Exception thrown is incorrect", cause, exception);
return;
}
fail("No exception has been re-thrown!");
}
@Test
public void callExceptionMeteredMethodOnceWithThrowingInstanceOfExpectedException() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
final RuntimeException exception = new IllegalStateException("message");
Runnable runnableThatThrowsIllegalStateException = new Runnable() {
@Override
public void run() {
throw exception;
}
};
// Call the metered method and assert it's been marked and that the original exception has been rethrown
try {
instance.exceptionMeteredMethod(runnableThatThrowsIllegalStateException);
} catch (RuntimeException cause) {
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(0L)));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(1L)));
assertSame("Exception thrown is incorrect", cause, exception);
return;
}
fail("No exception has been re-thrown!");
}
@Test
public void callExceptionMeteredStaticMethodsOnceWithoutThrowing() {
Runnable runnableThatDoesNoThrowExceptions = new Runnable() {
@Override
public void run() {
}
};
// Call the metered methods and assert they haven't been marked
MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);
MeteredStaticMethodWithExceptions.exceptionMeteredStaticMethod(runnableThatDoesNoThrowExceptions);
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
}
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingExpectedException() {
final RuntimeException exception = new IllegalArgumentException("message");
Runnable runnableThatThrowsIllegalArgumentException = new Runnable() {
@Override
public void run() {
throw exception;
}
};
// Call the metered method and assert it's been marked and that the original exception has been rethrown
try {
MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalArgumentException);
} catch (RuntimeException cause) {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].incrementAndGet())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
assertSame("Exception thrown is incorrect", cause, exception);
return;
}
fail("No exception has been re-thrown!");
}
@Test
public void callExceptionMeteredStaticMethodOnceWithThrowingNonExpectedException() {
final RuntimeException exception = new IllegalStateException("message");
Runnable runnableThatThrowsIllegalStateException = new Runnable() {
@Override
public void run() {
throw exception;
}
};
// Call the metered method and assert it hasn't been marked and that the original exception has been rethrown
try {
MeteredStaticMethodWithExceptions.illegalArgumentExceptionMeteredStaticMethod(runnableThatThrowsIllegalStateException);
} catch (RuntimeException cause) {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(absoluteMetricNames())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(0)).getCount(), is(equalTo(METER_COUNTS[0].get())));
assertThat("Meter count is incorrect", registry.getMeters().get(absoluteMetricName(1)).getCount(), is(equalTo(METER_COUNTS[1].get())));
assertSame("Exception thrown is incorrect", cause, exception);
return;
}
fail("No exception has been re-thrown!");
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
initTestObjects();
initDependencies();
this.managerUnderTest = new DetectorManager(detectorSource, dataInitializer, config, cachedDetectors, SharedMetricRegistries.getOrCreate("test"));
}
@Test
public void timedMethodNotCalledYet() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(timerName));
Timer timer = registry.getTimers().get(timerName);
// Make sure that the timer hasn't been called yet
assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(0L)));
}
@Test
public void overloadedTimedMethodNotCalledYet() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));
// Make sure that all the timers haven't been called yet
assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(0L))));
}
@Test
public void timedMethodsNotCalledYet() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));
// Make sure that all the timers haven't been called yet
assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(0L))));
}
@Before
public void setUp(TestContext context) {
String graphiteHost = System.getProperty("graphiteHost");
final String registryName = "okapi";
MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);
// Note the setEnabled (true or false)
DropwizardMetricsOptions metricsOpt = new DropwizardMetricsOptions().
setEnabled(false).setRegistryName(registryName);
vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(metricsOpt));
reporter1 = ConsoleReporter.forRegistry(registry).build();
reporter1.start(1, TimeUnit.SECONDS);
if (graphiteHost != null) {
Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, 2003));
reporter2 = GraphiteReporter.forRegistry(registry)
.prefixedWith("okapiserver")
.build(graphite);
reporter2.start(1, TimeUnit.MILLISECONDS);
}
DeploymentOptions opt = new DeploymentOptions()
.setConfig(new JsonObject().put("port", Integer.toString(port)));
vertx.deployVerticle(MainVerticle.class.getName(),
opt, context.asyncAssertSuccess());
httpClient = vertx.createHttpClient();
}
/**
* Return a set of existing registry names.
*/
public Set<String> registryNames() {
Set<String> set = new HashSet<>();
set.addAll(registries.keySet());
set.addAll(SharedMetricRegistries.names());
return set;
}
@Override
public void init(List<KafkaMetric> metrics) {
_registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
for (KafkaMetric kafkaMetric : metrics) {
metricChange(kafkaMetric);
}
}
@Test
public void timedMethodNotCalledYet() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(TIMER_NAME));
Timer timer = registry.getTimers().get(TIMER_NAME);
// Make sure that the timer hasn't been called yet
assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(0L)));
}
@Override
public void init(List<KafkaMetric> list) {
if (config == null) {
throw new IllegalStateException("Must call configure() before calling init() on a reporter.");
}
String registryName = config.getString(DropwizardReporterConfig.REGISTRY_PROPERTY_NAME);
this.registry = SharedMetricRegistries.getOrCreate(registryName);
for (KafkaMetric kafkaMetric : list) {
this.metricChange(kafkaMetric);
}
}
@Provides
public FluxRuntimeConnector provideFluxRuntimeConnector(FluxClientConfiguration configuration,
ObjectMapper objectMapper) {
String fluxRuntimeUrl = System.getProperty("flux.runtimeUrl");
if (fluxRuntimeUrl == null) {
fluxRuntimeUrl = configuration.getFluxRuntimeUrl();
}
return new FluxRuntimeConnectorHttpImpl(configuration.getConnectionTimeout(),
configuration.getSocketTimeout(),
fluxRuntimeUrl + "/api/machines",
objectMapper, SharedMetricRegistries.getOrCreate("mainMetricRegistry"));
}
private static void startReport() {
SharedMetricRegistries.add(ObjectRunner.REGISTRY_NAME, REGISTRY);
ConsoleReporter.forRegistry(REGISTRY)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.outputTo(new PrintStream(System.out))
.build()
.start(3, TimeUnit.SECONDS);
}
@Test
public void callLambdaExpressionTimedStaticMethodOnce() {
// Call the timed static method and assert it's been timed once
TimedStaticMethodWithNameFromElExpression.lambdaExpressionStaticTimedMethod();
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timer is not registered correctly", registry.getTimers(), hasKey(TIMER_NAME));
Timer timer = registry.getTimers().get(TIMER_NAME);
assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(TIMER_COUNT.incrementAndGet())));
}
@Test
public void callTimedMethodsOnce() {
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Timers are not registered correctly", registry.getTimers().keySet(), is(equalTo(absoluteMetricNames())));
// Call the timed methods and assert they've all been timed once
instance.publicTimedMethod();
instance.protectedTimedMethod();
instance.packagePrivateTimedMethod();
method("privateTimedMethod").in(instance).invoke();
assertThat("Timer counts are incorrect", registry.getTimers().values(), everyItem(Matchers.<Timer>hasProperty("count", equalTo(1L))));
}