Java Code Examples for com.codahale.metrics.SharedMetricRegistries#getOrCreate()

The following examples show how to use com.codahale.metrics.SharedMetricRegistries#getOrCreate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedriverService.java    From flux with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: CursorStore.java    From notification with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
}
 
Example 3
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@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!");
}
 
Example 4
Source File: JavaxElMetricStrategy.java    From metrics-aspectj with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example 5
Source File: GaugeStaticMethodWithRegistryFromStringTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@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)));
}
 
Example 6
Source File: DriverTest.java    From metrics-sql with Apache License 2.0 5 votes vote down vote up
@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"));

}
 
Example 7
Source File: MetricsExamples.java    From vertx-dropwizard-metrics with Apache License 2.0 5 votes vote down vote up
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
}
 
Example 8
Source File: FluxClientComponentModule.java    From flux with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 9
Source File: JavaSeMetricStrategy.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 10
Source File: TimedMethodWithRegistryFromSharedMetricRegistriesTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@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)));
}
 
Example 11
Source File: GuicePropertyFilteringMessageBodyWriter.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private MetricRegistry getMetricRegistry() {
  MetricRegistry registry = environment.metrics();

  if (registry == null) {
    LOG.warn("No environment metrics found!");
    registry = SharedMetricRegistries.getOrCreate("com.hubspot");
  }

  return registry;
}
 
Example 12
Source File: MetricsTest.java    From okapi with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: TimedMethodWithRegistryFromSharedMetricRegistriesTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@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)));
}
 
Example 14
Source File: MeteredMethodWithExceptionsTest.java    From metrics-aspectj with Apache License 2.0 5 votes vote down vote up
@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))));
}
 
Example 15
Source File: DashboardVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@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);
    });

}
 
Example 16
Source File: DetectorManagerTest.java    From adaptive-alerting with Apache License 2.0 4 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testBadConfig() {
    new DetectorManager(detectorSource, dataInitializer, badConfig, SharedMetricRegistries.getOrCreate("test"));
}
 
Example 17
Source File: Application.java    From vertx-in-production with MIT License 4 votes vote down vote up
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);
                });
    }
 
Example 18
Source File: NotificationListResolver.java    From notification with Apache License 2.0 4 votes vote down vote up
/** Constructor */
public NotificationListResolver() {
  final MetricRegistry registry = SharedMetricRegistries.getOrCreate("default");
  this.siblingCounts = registry.histogram(name(NotificationListResolver.class, "sibling-counts"));
}
 
Example 19
Source File: InstrumentedHandler.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public InstrumentedHandler(Handler delegate) {
  super(SharedMetricRegistries.getOrCreate("nexus"));
  setHandler(delegate);
}
 
Example 20
Source File: InstrumentedAppender.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public InstrumentedAppender() {
  super(SharedMetricRegistries.getOrCreate("nexus"));
}