下面列出了怎么用com.codahale.metrics.MetricSet的API类实例代码及写法,或者点击链接到github查看源代码。
private static final void registerIfPossible(String set, String className) {
try {
Class<?> clazz = Class.forName(className);
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
registerAll(set, (MetricSet)instance);
logger.debug("successfully registered metric set {}", set);
} catch (Throwable th) {
if (logger.isTraceEnabled()) {
logger.debug("unable to register metric set {}: {}", set, th.getMessage(), th);
} else {
logger.debug("unable to register metric set {}: {}", set, th.getMessage());
}
}
}
/**
* Register all metrics in the provided {@link MetricSet}, optionally skipping those that
* already exist.
*
* @param registry registry name
* @param metrics metric set to register
* @param strategy the conflict resolution strategy to use if the named metric already exists.
* @param metricPath (optional) additional top-most metric name path elements
* @throws Exception if a metric with this name already exists.
*/
public void registerAll(String registry, MetricSet metrics, ResolutionStrategy strategy, String... metricPath) throws Exception {
MetricRegistry metricRegistry = registry(registry);
synchronized (metricRegistry) {
Map<String, Metric> existingMetrics = metricRegistry.getMetrics();
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
String fullName = mkName(entry.getKey(), metricPath);
if (existingMetrics.containsKey(fullName)) {
if (strategy == ResolutionStrategy.REPLACE) {
metricRegistry.remove(fullName);
} else if (strategy == ResolutionStrategy.IGNORE) {
continue;
} // strategy == ERROR will fail when we try to register later
}
metricRegistry.register(fullName, entry.getValue());
}
}
}
private void configuration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
// Fire configuration event
manager.fireEvent(configuration);
configuration.unmodifiable();
// Produce and register custom metrics
MetricRegistry registry = getReference(manager, MetricRegistry.class);
MetricName metricName = getReference(manager, MetricName.class);
for (Map.Entry<Bean<?>, AnnotatedMember<?>> bean : metrics.entrySet()) {
// TODO: add MetricSet metrics into the metric registry
if (bean.getKey().getTypes().contains(MetricSet.class)
// skip non @Default beans
|| !bean.getKey().getQualifiers().contains(DEFAULT)
// skip producer methods with injection point
|| hasInjectionPoints(bean.getValue()))
continue;
registry.register(metricName.of(bean.getValue()), (Metric) getReference(manager, bean.getValue().getBaseType(), bean.getKey()));
}
// Let's clear the collected metric producers
metrics.clear();
}
private void registerAll(String prefix, MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue());
} else {
metricRegistry.register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
private static void registerAll(String prefix, MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue());
} else {
if (!(registry.getNames().contains(prefix + "." + entry.getKey()))) {
registry.register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
}
public static void unregisterAll(MetricSet set) {
if (set != null) {
for (String name : set.getMetrics().keySet()) {
IrisMetrics.registry().remove(name);
}
}
}
@Override public void registerAll(String prefix, MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue());
} else {
register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
private static MetricSet scoped(final String name, final MetricSet metricSet) {
return new MetricSet() {
@Override
public Map<String, Metric> getMetrics() {
ImmutableMap.Builder<String, Metric> scopedMetrics = ImmutableMap.builder();
for(Map.Entry<String, Metric> entry: metricSet.getMetrics().entrySet()) {
scopedMetrics.put(MetricRegistry.name(name, entry.getKey()), entry.getValue());
}
return scopedMetrics.build();
}
};
}
/**
* Create a new reporter that reports the top slow operations over time.
* @param name The name of the metric
* @param count The number of items to keep (eg 10 for top 10)
* @param latencyThreshold The latency below which observations should be ignored.
* @param reset The desired reset behavior.
* @return The reporter to use.
*/
public static synchronized TopMonitor newTopReporter(String name, int count, Duration latencyThreshold, ResetType reset) {
TopBuilder builder = Top.builder(count).withLatencyThreshold(latencyThreshold);
switch(reset) {
case NEVER:
builder.neverResetPositions();
break;
case ON_SNAPSHOT:
builder.resetAllPositionsOnSnapshot();
break;
case PERIODIC_15M:
case PERIODIC_1D:
case PERIODIC_7D:
builder.resetAllPositionsPeriodically(reset.getDuration());
break;
case PERIODIC_DECAY:
builder.resetPositionsPeriodicallyByChunks(reset.getDuration(), DECAY_CHUNKS);
break;
default:
throw new UnsupportedOperationException("Unknown type: " + reset);
}
Top top = builder.build();
MetricSet metricSet = new TopMetricSet(name, top, TimeUnit.MILLISECONDS, 2);
RegistryHolder.REGISTRY.registerAll(metricSet);
return (latency, desc, tags) -> top.update(System.currentTimeMillis(), latency, TimeUnit.MILLISECONDS, () -> desc.get());
}
@PostConstruct
public void init() {
// ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metricRegistry)
// .convertRatesTo(TimeUnit.SECONDS)
// .convertDurationsTo(TimeUnit.MILLISECONDS)
// .build();
//
// consoleReporter.start(10, TimeUnit.SECONDS);
// Graphite graphite = new Graphite(new InetSocketAddress("192.168.99.100", 2003));
// GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(metricRegistry)
// .prefixedWith("com.packt.microservices.geolocation")
// .convertRatesTo(TimeUnit.SECONDS)
// .convertDurationsTo(TimeUnit.MILLISECONDS)
// .filter(MetricFilter.ALL)
// .build(graphite);
// graphiteReporter.start(60, TimeUnit.SECONDS);
geolocationWriteRequestCount = metricRegistry.counter("geolocationWriteRequestCount");
metricRegistry.register("geolocationLastWriteTime", new Gauge<Long>() {
@Override
public Long getValue() {
return geolocationLastWriteTime;
}
});
metricRegistry.registerAll(new MetricSet() {
@Override
public Map<String, Metric> getMetrics() {
Map<String, Metric> metrics = new HashMap<>();
metrics.put("geolocationMemoryUsage", new MemoryUsageGaugeSet());
metrics.put("geolocationClassLoading", new ClassLoadingGaugeSet());
metrics.put("geolocationGarbageCollector", new GarbageCollectorMetricSet());
return metrics;
}
});
}
@SuppressWarnings("UnusedReturnValue")
public @NotNull CodahaleMetricsCollector registerAll(String prefix, @NotNull MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue());
}
else {
registerNamedMetric(prefix + "." + entry.getKey(), entry.getValue());
}
}
return this;
}
private void registerAll(String prefix, MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue());
} else {
metricRegistry.register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
private void registerJvmMetrics() {
registerMetricSetWithPrefix("jvm.gc", new GarbageCollectorMetricSet());
registerMetricSetWithPrefix("jvm.memory", new MemoryUsageGaugeSet());
registerMetricSetWithPrefix("jvm.threads", new ThreadStatesGaugeSet());
this.metricRegistry.register("jvm.fileDescriptorRatio", new FileDescriptorRatioGauge());
for (Map.Entry<String, MetricSet> metricSet : this.additionalMetricSets.entrySet()) {
registerMetricSetWithPrefix(metricSet.getKey(), metricSet.getValue());
}
}
private void registerAll(String prefix, MetricSet metrics) throws IllegalArgumentException {
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(MetricRegistry.name(prefix, entry.getKey()), (MetricSet) entry.getValue());
} else {
metricRegistry.register(MetricRegistry.name(prefix, entry.getKey()), entry.getValue());
}
}
}
private void registerMetricSet(String prefix, MetricSet metricSet, MetricRegistry registry) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerMetricSet(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry);
} else {
registry.register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
private void registerAll(String prefix, MetricSet metrics, MetricRegistry registry) {
for (Map.Entry<String, Metric> entry : metrics.getMetrics().entrySet()) {
String name = MetricRegistry.name(prefix, entry.getKey());
if (entry.getValue() instanceof MetricSet) {
registerAll(name, (MetricSet) entry.getValue(), registry);
} else {
register(name, entry.getValue(), registry);
}
}
}
public static void registerAll(MetricSet set) {
if (set != null) {
IrisMetrics.registry().registerAll(set);
}
}
private MetricSet metricsFor(String cacheName, final Cache cache) {
HashMap<String, Metric> metrics = new HashMap<>();
metrics.put(name(cacheName, "requestCount"), (Gauge<Long>) () -> cache.stats().requestCount());
metrics.put(name(cacheName, "hitCount"), (Gauge<Long>) () -> cache.stats().hitCount());
metrics.put(name(cacheName, "hitRate"), (Gauge<Double>) () -> cache.stats().hitRate());
metrics.put(name(cacheName, "missCount"), (Gauge<Long>) () -> cache.stats().missCount());
metrics.put(name(cacheName, "missRate"), (Gauge<Double>) () -> cache.stats().missRate());
metrics.put(name(cacheName, "evictionCount"), (Gauge<Long>) () -> cache.stats().evictionCount());
metrics.put(name(cacheName, "exceptionCount"), (Gauge<Long>) () -> cache.stats().loadExceptionCount());
metrics.put(name(cacheName, "exceptionRate"), (Gauge<Double>) () -> cache.stats().loadExceptionRate());
metrics.put(name(cacheName, "totalLoadTime"), (Gauge<Long>) () -> cache.stats().totalLoadTime());
metrics.put(name(cacheName, "size"), (Gauge<Long>) cache::size);
return () -> metrics;
}
public void registerAll(MetricSet metrics) {
registry.registerAll(metrics);
}
@Override
public MetricSet getMetricSet() {
return null;
}
public MetricSet getMetricSet() {
return () -> metrics;
}
public MetricSet getTaskExecutorQueueMetricSet() {
return this.metricSet;
}
public JMXReportingService(Map<String, MetricSet> additionalMetricSets) {
this.additionalMetricSets = additionalMetricSets;
}
private void registerMetricSetWithPrefix(String prefix, MetricSet metricSet) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
this.metricRegistry.register(MetricRegistry.name(prefix, entry.getKey()), entry.getValue());
}
}
@Override
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
throw new UnsupportedOperationException();
}
@Override
public MetricSet getMetricSet() {
return localRegistry;
}
@Override
public MetricSet getMetricSet() {
return localRegistry;
}
void registerAll(String prefix, MetricSet metricSet);