下面列出了com.codahale.metrics.SharedMetricRegistries#getOrCreate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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!");
}
@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 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");
}
@Inject
public RedriverService(MessageManagerService messageService,
RedriverRegistry redriverRegistry,
@Named("redriver.batchRead.intervalms") Integer batchReadInterval,
@Named("redriver.batchRead.batchSize") Integer batchSize) {
this.redriverRegistry = redriverRegistry;
this.batchReadInterval = batchReadInterval;
this.batchSize = batchSize;
this.messageService = messageService;
asyncRedriveService = Executors.newFixedThreadPool(10);
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 callStaticGaugeAfterSetterCall() {
long value = Math.round(Math.random() * Long.MAX_VALUE);
// Call the setter static method and assert the gauge is up-to-date
GaugeStaticMethodWithRegistryFromString.setSingleGauge(value);
assertThat("Shared metric registry is not created", SharedMetricRegistries.names(), hasItem(REGISTRY_NAME));
MetricRegistry registry = SharedMetricRegistries.getOrCreate(REGISTRY_NAME);
assertThat("Gauge is not registered correctly", registry.getGauges(), hasKey(GAUGE_NAME));
@SuppressWarnings("unchecked")
Gauge<Long> gauge = registry.getGauges().get(GAUGE_NAME);
assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(value)));
}
@Test
public void exceptionMeteredMethodsNotCalledYet() {
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())));
// Make sure that all the meters haven't been called yet
assertThat("Meter counts are incorrect", registry.getMeters().values(), everyItem(Matchers.<Meter>hasProperty("count", equalTo(0L))));
}
@Test
public void callTimedMethodOnce() {
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);
// Call the timed method and assert it's been timed
instance.singleTimedMethod();
assertThat("Timer count is incorrect", timer.getCount(), is(equalTo(1L)));
}
@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();
}
private MetricRegistry getMetricRegistry() {
MetricRegistry registry = environment.metrics();
if (registry == null) {
LOG.warn("No environment metrics found!");
registry = SharedMetricRegistries.getOrCreate("com.hubspot");
}
return registry;
}
@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 MetricRegistry resolveMetricRegistry(String registry) {
Matcher matcher = EL_PATTERN.matcher(registry);
if (matcher.find())
throw new UnsupportedOperationException("Unsupported EL expression [" + registry + "] evaluation as no EL implementation is available");
else
return SharedMetricRegistries.getOrCreate(registry);
}
@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"));
}
public void getRegistry() {
VertxOptions options = new VertxOptions().setMetricsOptions(
new DropwizardMetricsOptions().setEnabled(true).setRegistryName("my-registry")
);
Vertx vertx = Vertx.vertx(options);
// Get the registry
MetricRegistry registry = SharedMetricRegistries.getOrCreate("my-registry");
// Do whatever you need with the registry
}
@Test
public void testStatementExec() throws SQLException {
// Act
Connection connection = DriverManager.getConnection(URL + ";metrics_registry=exec", H2DbUtil.USERNAME, H2DbUtil.PASSWORD);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select CURRENT_DATE");
H2DbUtil.close(resultSet, statement, connection);
// Assert
assertNotNull(connection);
assertTrue(Proxy.isProxyClass(resultSet.getClass()));
MetricRegistry metricRegistry = SharedMetricRegistries.getOrCreate("exec");
assertNotNull(metricRegistry.getTimers().get("java.sql.Statement.[select current_date].exec"));
}
public static void main(String[] args) {
System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.SLF4JLogDelegateFactory");
// Initialize metric registry
String registryName = "registry";
MetricRegistry registry = SharedMetricRegistries.getOrCreate(registryName);
SharedMetricRegistries.setDefault(registryName);
Slf4jReporter reporter = Slf4jReporter.forRegistry(registry)
.outputTo(LoggerFactory.getLogger(Application.class))
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.start(1, TimeUnit.MINUTES);
// Initialize vertx with the metric registry
DropwizardMetricsOptions metricsOptions = new DropwizardMetricsOptions()
.setEnabled(true)
.setMetricRegistry(registry);
VertxOptions vertxOptions = new VertxOptions().setMetricsOptions(metricsOptions);
Vertx vertx = Vertx.vertx(vertxOptions);
ConfigRetrieverOptions configRetrieverOptions = getConfigRetrieverOptions();
ConfigRetriever configRetriever = ConfigRetriever.create(vertx, configRetrieverOptions);
// getConfig is called for initial loading
configRetriever.getConfig(
ar -> {
int instances = Runtime.getRuntime().availableProcessors();
DeploymentOptions deploymentOptions =
new DeploymentOptions().setInstances(instances).setConfig(ar.result());
vertx.deployVerticle(MainVerticle.class, deploymentOptions);
});
// listen is called each time configuration changes
configRetriever.listen(
change -> {
JsonObject updatedConfiguration = change.getNewConfiguration();
vertx.eventBus().publish(EventBusChannels.CONFIGURATION_CHANGED.name(), updatedConfiguration);
});
}
@Test(expected = IllegalArgumentException.class)
public void testBadConfig() {
new DetectorManager(detectorSource, dataInitializer, badConfig, SharedMetricRegistries.getOrCreate("test"));
}
@Override
public void start() throws Exception {
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
options
.addOutboundPermitted(new PermittedOptions().setAddress("market"))
.addOutboundPermitted(new PermittedOptions().setAddress("portfolio"))
.addOutboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
.addInboundPermitted(new PermittedOptions().setAddress("service.portfolio"))
.addOutboundPermitted(new PermittedOptions().setAddress("vertx.circuit-breaker"));
sockJSHandler.bridge(options);
router.route("/eventbus/*").handler(sockJSHandler);
// Last operations
router.get("/operations").handler(this::callAuditService);
router.get("/health").handler(rc -> rc.response().end("OK"));
MetricRegistry dropwizardRegistry = SharedMetricRegistries.getOrCreate(
System.getProperty("vertx.metrics.options.registryName")
);
ServiceDiscovery.create(vertx, discovery -> {
this.discovery = discovery;
WebConsoleRegistry.create("/admin")
// Add pages
.addPage(MetricsConsolePage.create(dropwizardRegistry))
.addPage(new TraderPage())
.addPage(ServicesConsolePage.create(discovery))
.addPage(CircuitBreakersConsolePage.create())
.setCacheBusterEnabled(true) // Adds random query string to scripts
// Mount to router
.mount(vertx, router);
retrieveAuditService();
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(8080);
});
}
/** Constructor */
public NotificationListResolver() {
final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
this.siblingCounts = registry.histogram(name(NotificationListResolver.class, "sibling-counts"));
}
public InstrumentedHandler(Handler delegate) {
super(SharedMetricRegistries.getOrCreate("nexus"));
setHandler(delegate);
}
public InstrumentedAppender() {
super(SharedMetricRegistries.getOrCreate("nexus"));
}