java类com.codahale.metrics.MetricRegistry的实例源码

TestSimpleLimit.java 文件源码 项目:QDrill 阅读 24 收藏 0 点赞 0 评论 0
@Test
@Ignore
// The testcase is not valid. "test4.json" using increasingBigInt(0) to generate a list of increasing number starting from 0, and verify the sum.
// However, when evaluate the increasingBitInt(0), if the outgoing batch could not hold the new value, doEval() return false, and start the
// next batch. But the value has already been increased by 1 in the prior failed try. Therefore, the sum of the generated number could be different,
// depending on the size of each outgoing batch, and when the batch could not hold any more values.
public void testLimitAcrossBatches(@Injectable final DrillbitContext bitContext, @Injectable UserServer.UserClientConnection connection) throws Throwable {
  new NonStrictExpectations(){{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
    bitContext.getConfig(); result = c;
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
  }};

  verifyLimitCount(bitContext, connection, "test2.json", 69999);
  final long start = 30000;
  final long end = 100000;
  final long expectedSum = (end - start) * (end + start - 1) / 2; //Formula for sum of series

  verifySum(bitContext, connection, "test4.json", 70000, expectedSum);


}
KafkaCruiseControl.java 文件源码 项目:cruise-control 阅读 27 收藏 0 点赞 0 评论 0
/**
 * Construct the Cruise Control
 *
 * @param config the configuration of Cruise Control.
 */
public KafkaCruiseControl(KafkaCruiseControlConfig config) {
  _config = config;
  _time = new SystemTime();
  // initialize some of the static state of Kafka Cruise Control;
  Load.init(config);
  ModelUtils.init(config);
  ModelParameters.init(config);
  _dropwizardMetricRegistry = new MetricRegistry();
  _reporter = JmxReporter.forRegistry(_dropwizardMetricRegistry).inDomain(_metricsPrefix).build();

  // Instantiate the components.
  _loadMonitor = new LoadMonitor(config, _time, _dropwizardMetricRegistry);
  _goalOptimizerExecutor =
      Executors.newSingleThreadExecutor(new KafkaCruiseControlThreadFactory("GoalOptimizerExecutor", true, null));
  _goalOptimizer = new GoalOptimizer(config, _loadMonitor, _time, _dropwizardMetricRegistry);
  _executor = new Executor(config, _time, _dropwizardMetricRegistry);
  _anomalyDetector = new AnomalyDetector(config, _loadMonitor, this, _time, _dropwizardMetricRegistry);
}
GraphiteMeterRegistry.java 文件源码 项目:micrometer 阅读 22 收藏 0 点赞 0 评论 0
private static GraphiteReporter defaultGraphiteReporter(GraphiteConfig config, MetricRegistry metricRegistry) {
    GraphiteSender sender;
    switch (config.protocol()) {
        case Plaintext:
            sender = new Graphite(new InetSocketAddress(config.host(), config.port()));
            break;
        case Udp:
            sender = new GraphiteUDP(new InetSocketAddress(config.host(), config.port()));
            break;
        case Pickled:
        default:
            sender = new PickledGraphite(new InetSocketAddress(config.host(), config.port()));
    }

    return GraphiteReporter.forRegistry(metricRegistry)
        .convertRatesTo(config.rateUnits())
        .convertDurationsTo(config.durationUnits())
        .build(sender);
}
TestHashTable.java 文件源码 项目:QDrill 阅读 23 收藏 0 点赞 0 评论 0
@SuppressWarnings("deprecation")
private SimpleRootExec doTest(final DrillbitContext bitContext, UserClientConnection connection, String plan_path) throws Exception{
    new NonStrictExpectations() {{
      bitContext.getMetrics(); result = new MetricRegistry();
      bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
      bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
      bitContext.getConfig(); result = c;
      bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
    }};

    final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
    final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile(plan_path), Charsets.UTF_8));
    final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
    final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
    final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
    return exec;
  }
DatadogConfiguration.java 文件源码 项目:sentry 阅读 28 收藏 0 点赞 0 评论 0
private DatadogReporter enableDatadogMetrics(MetricRegistry registry) {
    log.info("Initializing Datadog reporter on host: {} with period: {} seconds",
        getHost() == null ? "localhost" : getHost(), getPeriod());
    Transport transport = getApiKey() == null ?
        new UdpTransport.Builder().build() : new HttpTransport.Builder().withApiKey(getApiKey()).build();
    DatadogReporter reporter = DatadogReporter.forRegistry(registry)
        .withHost(getHost())
        .withTransport(transport)
        .withExpansions(expansions())
        .withTags(getTags())
        .withPrefix(getPrefix())
        .filter(getFilter())
        .withMetricNameFormatter(new CustomMetricNameFormatter())
        .build();
    reporter.start(getPeriod(), TimeUnit.SECONDS);
    log.info("Datadog reporter successfully initialized");
    return reporter;
}
JsonHandlerTest.java 文件源码 项目:ja-micro 阅读 29 收藏 0 点赞 0 评论 0
@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);
}
CSVReporter.java 文件源码 项目:jboot 阅读 26 收藏 0 点赞 0 评论 0
@Override
public void report(MetricRegistry metricRegistry) {

    JbootMetricsCVRReporterConfig cvrReporterConfig = Jboot.config(JbootMetricsCVRReporterConfig.class);

    if (StringUtils.isBlank(cvrReporterConfig.getPath())) {
        throw new NullPointerException("csv reporter path must not be null, please config jboot.metrics.reporter.cvr.path in you properties.");
    }

    final CsvReporter reporter = CsvReporter.forRegistry(metricRegistry)
            .formatFor(Locale.US)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build(new File(cvrReporterConfig.getPath()));

    reporter.start(1, TimeUnit.SECONDS);
}
MatchingServiceHealthCheckClient.java 文件源码 项目:verify-hub 阅读 30 收藏 0 点赞 0 评论 0
public MatchingServiceHealthCheckResponseDto sendHealthCheckRequest(
        final Element matchingServiceHealthCheckRequest,
        final URI matchingServiceUri) {

    // Use a custom timer so that we get separate metrics for each matching service
    final String scope = matchingServiceUri.toString().replace(':','_').replace('/', '_');
    final Timer timer = metricsRegistry.timer(MetricRegistry.name(MatchingServiceHealthCheckClient.class, "sendHealthCheckRequest", scope));
    final Timer.Context context = timer.time();
    HealthCheckResponse healthCheckResponse;
    try {
        healthCheckResponse = client.makeSoapRequestForHealthCheck(matchingServiceHealthCheckRequest, matchingServiceUri);
    } catch(ApplicationException ex) {
        final String errorMessage = MessageFormat.format("Failed to complete matching service health check to {0}.", matchingServiceUri);
        LOG.warn(errorMessage, ex);
        return new MatchingServiceHealthCheckResponseDto(Optional.<String>absent(), Optional.<String>absent());
    } finally {
        context.stop();
    }

    return new MatchingServiceHealthCheckResponseDto(
                Optional.of(XmlUtils.writeToString(healthCheckResponse.getResponseElement())),
                healthCheckResponse.getVersionNumber());
}
DefaultGroupStorage.java 文件源码 项目:outland 阅读 35 收藏 0 点赞 0 评论 0
@Inject
public DefaultGroupStorage(
    AmazonDynamoDB amazonDynamoDB,
    TableConfiguration tableConfiguration,
    @Named("dynamodbGroupWriteHystrix") HystrixConfiguration dynamodbGroupWriteHystrix,
    @Named("dynamodbGraphWriteHystrix") HystrixConfiguration dynamodbGraphWriteHystrix,
    @Named("dynamodbNamespaceGraphQueryHystrix")
        HystrixConfiguration dynamodbNamespaceGraphQueryHystrix,
    MetricRegistry metrics
) {
  this.amazonDynamoDB = amazonDynamoDB;
  this.dynamoDB = new DynamoDB(this.amazonDynamoDB);
  this.groupTableName = tableConfiguration.outlandGroupsTable;
  this.groupGraphTableName = tableConfiguration.outlandAppGraphTable;
  this.dynamodbGroupWriteHystrix = dynamodbGroupWriteHystrix;
  this.dynamodbGraphWriteHystrix = dynamodbGraphWriteHystrix;
  this.dynamodbNamespaceGraphQueryHystrix = dynamodbNamespaceGraphQueryHystrix;
  this.metrics = metrics;
}
ListAddBenchmark.java 文件源码 项目:redisson-benchmark 阅读 27 收藏 0 点赞 0 评论 0
public static void main(String[] args) throws InterruptedException {
    Bench<JedisPool> bench = new JedisBench() {
        @Override
        public void executeOperation(String data, JedisPool benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            Jedis jedis = benchInstance.getResource();

            Timer.Context time = metrics.timer("list").time();
            String key = "list_" + threadNumber;
            jedis.rpush(key, data);
            time.stop();

            jedis.close();
        }
    };

    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
RaftLogWorker.java 文件源码 项目:incubator-ratis 阅读 31 收藏 0 点赞 0 评论 0
RaftLogWorker(RaftPeerId selfId, RaftServerImpl raftServer, RaftStorage storage,
              RaftProperties properties) {
  this.name = selfId + "-" + getClass().getSimpleName();
  LOG.info("new {} for {}", name, storage);

  this.raftServer = raftServer;
  this.stateMachine = raftServer != null? raftServer.getStateMachine(): null;

  this.storage = storage;
  this.segmentMaxSize =
      RaftServerConfigKeys.Log.segmentSizeMax(properties).getSize();
  this.preallocatedSize =
      RaftServerConfigKeys.Log.preallocatedSize(properties).getSize();
  this.bufferSize =
      RaftServerConfigKeys.Log.writeBufferSize(properties).getSizeInt();
  this.forceSyncNum = RaftServerConfigKeys.Log.forceSyncNum(properties);
  this.workerThread = new Thread(this, name);

  // Server Id can be null in unit tests
  Supplier<String> serverId = () -> raftServer == null || raftServer.getId() == null
      ? "null" : raftServer.getId().toString();
  this.logFlushTimer = JavaUtils.memoize(() -> RatisMetricsRegistry.getRegistry()
      .timer(MetricRegistry.name(RaftLogWorker.class, serverId.get(),
          "flush-time")));
}
DistCpCopier.java 文件源码 项目:circus-train 阅读 22 收藏 0 点赞 0 评论 0
public DistCpCopier(
    Configuration conf,
    Path sourceDataBaseLocation,
    List<Path> sourceDataLocations,
    Path replicaDataLocation,
    Map<String, Object> copierOptions,
    MetricRegistry registry) {
  this(conf, sourceDataBaseLocation, sourceDataLocations, replicaDataLocation, copierOptions, DistCpExecutor.DEFAULT,
      registry);
}
WebConfigurerTest.java 文件源码 项目:jhipster-microservices-example 阅读 30 收藏 0 点赞 0 评论 0
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(new MockFilterRegistration())
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(new MockServletRegistration())
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props, new MockHazelcastInstance());
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
DemoInitializer.java 文件源码 项目:geode-exposing-metrics-via-JMX 阅读 21 收藏 0 点赞 0 评论 0
private void checkForMatchAndAdd(StatisticsType type, String[] statsRegularExpression, Statistics currStatistics, StatisticDescriptor currDesciptor) {
    for (String currRegex : statsRegularExpression) {
        if (Pattern.matches(currRegex, currDesciptor.getName())) {
            MyInternalGauge gauge = new MyInternalGauge(currStatistics, currDesciptor);
            metricRegistry.register(MetricRegistry.name(type.getName(), currStatistics.getTextId(), currDesciptor.getName()), gauge);
        }
    }
}
HikariDataSourceFactory.java 文件源码 项目:dropwizard-hikaricp-benchmark 阅读 28 收藏 0 点赞 0 评论 0
@Override
public ManagedDataSource build(final MetricRegistry metricRegistry, final String name) {
    final Properties properties = new Properties();
    for (final Map.Entry<String, String> property : this.properties.entrySet()) {
        properties.setProperty(property.getKey(), property.getValue());
    }

    final HikariConfig config = new HikariConfig();
    config.setMetricRegistry(metricRegistry);
    if (healthCheckRegistry != null) {
        config.setHealthCheckRegistry(healthCheckRegistry);
    }

    config.setAutoCommit(autoCommit);
    config.setDataSourceProperties(properties);
    if (datasourceClassName != null) {
        config.setDataSourceClassName(datasourceClassName);
    } else {
        config.setDriverClassName(driverClass);
    }

    config.setMaximumPoolSize(maxSize);
    minSize.ifPresent(config::setMinimumIdle);
    config.setPoolName(name);
    config.setUsername(user);
    config.setPassword(user != null && password == null ? "" : password);
    return new HikariManagedPooledDataSource(config);
}
InfluxDbHttpWriter.java 文件源码 项目:dropwizard-influxdb-reporter 阅读 19 收藏 0 点赞 0 评论 0
public InfluxDbWriter build(final MetricRegistry metrics) {
  final Client client = new io.dropwizard.client.JerseyClientBuilder(metrics)
    .using(jersey)
    .using(new ObjectMapper())
    .using(Executors.newSingleThreadExecutor())
    .build("influxdb-http-writer");

  try {
    final String query = "/write?db=" + URLEncoder.encode(database, "UTF-8");
    final URL endpoint = new URL("http", host, port, query);
    return new InfluxDbHttpWriter(client, endpoint.toString());
  } catch (MalformedURLException | UnsupportedEncodingException e) {
    throw new IllegalArgumentException(e);
  }
}
WebConfigurerTest.java 文件源码 项目:jhipster-microservices-example 阅读 38 收藏 0 点赞 0 评论 0
@Before
public void setup() {
    servletContext = spy(new MockServletContext());
    doReturn(new MockFilterRegistration())
        .when(servletContext).addFilter(anyString(), any(Filter.class));
    doReturn(new MockServletRegistration())
        .when(servletContext).addServlet(anyString(), any(Servlet.class));

    env = new MockEnvironment();
    props = new JHipsterProperties();

    webConfigurer = new WebConfigurer(env, props);
    metricRegistry = new MetricRegistry();
    webConfigurer.setMetricRegistry(metricRegistry);
}
EitherMessageBodyWriterTest.java 文件源码 项目:dropwizard-vavr 阅读 24 收藏 0 点赞 0 评论 0
@Override
protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    return DropwizardResourceConfig.forTesting(new MetricRegistry())
            .register(EitherMessageBodyWriter.class)
            .register(EmptyValueExceptionMapper.class)
            .register(TestResource.class);
}
NbdStatsReporter.java 文件源码 项目:minebox 阅读 30 收藏 0 点赞 0 评论 0
@Inject
public NbdStatsReporter(MetricRegistry metrics) {
    ScheduledReporter reporter = Slf4jReporter.forRegistry(metrics)
            .withLoggingLevel(Slf4jReporter.LoggingLevel.DEBUG)
            .outputTo(LOGGER)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS)
            .build();
    reporter.start(5, TimeUnit.SECONDS);
}
BinaryBenchmark.java 文件源码 项目:redisson-benchmark 阅读 26 收藏 0 点赞 0 评论 0
public static void main(String[] args) throws InterruptedException {
    Bench<RedissonClient> bench = new RedissonBench() {
        @Override
        public void executeOperation(String data, RedissonClient benchInstance, int threadNumber, int iteration,
                MetricRegistry metrics) {
            RBucket<Object> bucket = benchInstance.getBucket("bucket_" + threadNumber + "_" + iteration);
            Timer.Context time = metrics.timer("bucket").time();
            bucket.set(value);
            time.stop();
        }
    };

    Benchmark benchmark = new Benchmark(bench);
    benchmark.run(args);
}
DefaultGangliaMetricsReporter.java 文件源码 项目:athena 阅读 34 收藏 0 点赞 0 评论 0
/**
 * Filters the metrics to only include a set of the given metrics.
 *
 * @param metricRegistry original metric registry
 * @return filtered metric registry
 */
protected MetricRegistry filter(MetricRegistry metricRegistry) {
    if (!monitorAll) {
        final MetricRegistry filtered = new MetricRegistry();
        metricRegistry.getNames().stream().filter(name ->
                containsName(name, metricNames)).forEach(name ->
                filtered.register(name, metricRegistry.getMetrics().get(name)));
        return filtered;
    } else {
        return metricRegistry;
    }
}
LoadMonitor.java 文件源码 项目:cruise-control 阅读 41 收藏 0 点赞 0 评论 0
/**
 * Construct a load monitor.
 *
 * @param config The load monitor configuration.
 * @param time   The time object.
 * @param dropwizardMetricRegistry the sensor registry for Cruise Control
 */
public LoadMonitor(KafkaCruiseControlConfig config,
                   Time time,
                   MetricRegistry dropwizardMetricRegistry) {
  this(config,
       new MetadataClient(config,
                          new Metadata(5000L, config.getLong(KafkaCruiseControlConfig.METADATA_MAX_AGE_CONFIG)),
                          METADATA_TTL,
                          time),
       time,
       dropwizardMetricRegistry);
}
DropwizardMeterRegistry.java 文件源码 项目:micrometer 阅读 30 收藏 0 点赞 0 评论 0
public DropwizardMeterRegistry(DropwizardConfig config, MetricRegistry registry, HierarchicalNameMapper nameMapper, Clock clock) {
    super(clock);
    this.dropwizardConfig = config;
    this.dropwizardClock = new DropwizardClock(clock);
    this.registry = registry;
    this.nameMapper = nameMapper;
    this.config().namingConvention(NamingConvention.camelCase);
}
Executor.java 文件源码 项目:cruise-control 阅读 37 收藏 0 点赞 0 评论 0
/**
 * The executor class that execute the proposals generated by optimizer.
 *
 * @param config The configurations for Cruise Control.
 */
public Executor(KafkaCruiseControlConfig config, Time time, MetricRegistry dropwizardMetricRegistry) {
  _executionTaskManager =
      new ExecutionTaskManager(config.getInt(KafkaCruiseControlConfig.NUM_CONCURRENT_PARTITION_MOVEMENTS_PER_BROKER_CONFIG),
                               config.getInt(KafkaCruiseControlConfig.NUM_CONCURRENT_LEADER_MOVEMENTS_CONFIG),
                               dropwizardMetricRegistry);
  _zkConnect = config.getString(KafkaCruiseControlConfig.ZOOKEEPER_CONNECT_CONFIG);
  _metadataClient = new MetadataClient(config, new Metadata(), -1L, time);
  _statusCheckingIntervalMs = config.getLong(KafkaCruiseControlConfig.EXECUTION_PROGRESS_CHECK_INTERVAL_MS_CONFIG);
  _excludedTopics = Pattern.compile(config.getString(KafkaCruiseControlConfig.TOPICS_EXCLUDED_FROM_PARTITION_MOVEMENT_CONFIG));
  _proposalExecutor =
      Executors.newSingleThreadExecutor(new KafkaCruiseControlThreadFactory("ProposalExecutor", false, LOG));
  _state = new AtomicReference<>(ExecutorState.State.NO_TASK_IN_PROGRESS);
  _stopRequested = false;
}
ExecutionTaskManager.java 文件源码 项目:cruise-control 阅读 25 收藏 0 点赞 0 评论 0
/**
 * The constructor of The Execution task manager.
 *
 * @param partitionMovementConcurrency The maximum number of concurrent partition movements per broker.
 */
public ExecutionTaskManager(int partitionMovementConcurrency,
                            int leaderMovementConcurrency,
                            MetricRegistry dropwizardMetricRegistry) {
  _inProgressPartMovementsByBrokerId = new HashMap<>();
  _inProgressPartitions = new HashSet<>();
  _executionTaskTracker = new ExecutionTaskTracker();
  _executionTaskPlanner = new ExecutionTaskPlanner();
  _partitionMovementConcurrency = partitionMovementConcurrency;
  _leaderMovementConcurrency = leaderMovementConcurrency;
  _brokersToSkipConcurrencyCheck = new HashSet<>();

  // Register gauge sensors.
  registerGaugeSensors(dropwizardMetricRegistry);
}
TestTraceMultiRecordBatch.java 文件源码 项目:QDrill 阅读 26 收藏 0 点赞 0 评论 0
@Test
public void testFilter(@Injectable final DrillbitContext bitContext, @Injectable UserClientConnection connection) throws Throwable {
  new NonStrictExpectations() {{
    bitContext.getMetrics(); result = new MetricRegistry();
    bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
    bitContext.getConfig(); result = c;
    bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(c);
    bitContext.getCompiler(); result = CodeCompiler.getTestCompiler(c);
  }};

  final PhysicalPlanReader reader = new PhysicalPlanReader(c, c.getMapper(), CoordinationProtos.DrillbitEndpoint.getDefaultInstance());
  final PhysicalPlan plan = reader.readPhysicalPlan(Files.toString(FileUtils.getResourceAsFile("/trace/multi_record_batch_trace.json"), Charsets.UTF_8));
  final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(c);
  final FragmentContext context = new FragmentContext(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
  final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));

  while(exec.next()) {
    for(final ValueVector vv: exec){
      vv.clear();
    }
  }

  exec.close();

  if(context.getFailureCause() != null) {
    throw context.getFailureCause();
  }
  assertTrue(!context.isFailed());
}
S3S3CopierFactory.java 文件源码 项目:circus-train 阅读 25 收藏 0 点赞 0 评论 0
@Autowired
public S3S3CopierFactory(
    AmazonS3ClientFactory clientFactory,
    ListObjectsRequestFactory listObjectsRequestFactory,
    TransferManagerFactory transferManagerFactory,
    MetricRegistry runningMetricsRegistry) {
  this.clientFactory = clientFactory;
  this.listObjectsRequestFactory = listObjectsRequestFactory;
  this.transferManagerFactory = transferManagerFactory;
  this.runningMetricsRegistry = runningMetricsRegistry;
}
LoadMonitorTaskRunnerTest.java 文件源码 项目:cruise-control 阅读 27 收藏 0 点赞 0 评论 0
@Test
public void testSamplingError() {
  KafkaCruiseControlConfig config = new KafkaCruiseControlConfig(getLoadMonitorProperties());
  Metadata metadata = new Metadata();
  MetadataClient metadataClient = new MetadataClient(config, metadata, -1L, TIME);
  MockMetricSampleAggregator mockMetricSampleAggregator = new MockMetricSampleAggregator(config, metadata);
  List<MetricSampler> samplers = new ArrayList<>();
  MetricRegistry dropwizardMetricRegistry = new MetricRegistry();
  for (int i = 0; i < NUM_METRIC_FETCHERS; i++) {
    samplers.add(new MockSampler(i));
  }
  MetricFetcherManager fetcherManager = new MetricFetcherManager(config, mockMetricSampleAggregator, metadataClient,
                                                                 TIME, dropwizardMetricRegistry, samplers);
  LoadMonitorTaskRunner loadMonitorTaskRunner =
      new LoadMonitorTaskRunner(config, fetcherManager, mockMetricSampleAggregator, metadataClient, TIME);
  while (metadata.fetch().topics().size() < 100) {
    metadataClient.refreshMetadata();
  }
  loadMonitorTaskRunner.start(true);

  int numSamples = 0;
  long startMs = System.currentTimeMillis();
  BlockingQueue<PartitionMetricSample> sampleQueue = mockMetricSampleAggregator.metricSampleQueue();
  while (numSamples < (NUM_PARTITIONS * NUM_TOPICS) * 10 && System.currentTimeMillis() < startMs + 10000) {
    PartitionMetricSample sample = sampleQueue.poll();
    if (sample != null) {
      numSamples++;
    }
  }
  // We should have NUM_METRIC_FETCHER rounds of sampling. The first round only has one metric fetcher returns
  // samples, two fetchers return samples for the second round, three for the third and four for the forth round.
  // So the first round only has 1/4 of the total samples, then 2/4, 3/4 and all the samples.
  int expectedNumSamples = 0;
  for (int i = 0; i < NUM_METRIC_FETCHERS; i++) {
    expectedNumSamples += (NUM_TOPICS * NUM_PARTITIONS) * (i + 1) / NUM_METRIC_FETCHERS;
  }
  assertEquals("Only see " + numSamples + " samples. Expecting " + expectedNumSamples + " samples",
      expectedNumSamples, numSamples);
  fetcherManager.shutdown();
}
AuthenticatorFeature.java 文件源码 项目:dust-api 阅读 25 收藏 0 点赞 0 评论 0
public AuthenticatorFeature(
        final MetricRegistry metricRegistry,
        final AuthConfig authConfig
) {
    this.metricRegistry = metricRegistry;
    this.authConfig = authConfig;
}
TestDbPool.java 文件源码 项目:Spring-5.0-Cookbook 阅读 27 收藏 0 点赞 0 评论 0
@Before
public void init() {
    MetricRegistry metricRegistry = new MetricRegistry();

    this.logReporter = ConsoleReporter
            .forRegistry(metricRegistry)
            .build();
    logReporter.start(1, TimeUnit.MINUTES); 
    timer = metricRegistry.timer("connection");
}


问题


面经


文章

微信
公众号

扫码关注公众号