0
# Metrics Collection
1
2
Spring Boot Actuator integrates with Micrometer to provide comprehensive application metrics including JVM, HTTP, database, and custom metrics with support for various monitoring system exports.
3
4
## Capabilities
5
6
### Core Metrics Endpoint
7
8
Built-in endpoint for exposing application metrics.
9
10
```java { .api }
11
/**
12
* Endpoint to expose application metrics
13
*/
14
@Endpoint(id = "metrics")
15
public class MetricsEndpoint {
16
public MetricsEndpoint(MeterRegistry registry);
17
18
/**
19
* List all available metric names
20
*/
21
@ReadOperation
22
public MetricNamesDescriptor listNames();
23
24
/**
25
* Get specific metric with optional tags
26
*/
27
@ReadOperation
28
public MetricDescriptor metric(@Selector String requiredMetricName, @Nullable List<String> tag);
29
30
/**
31
* Response containing list of metric names
32
*/
33
public static final class MetricNamesDescriptor {
34
public Set<String> getNames();
35
}
36
37
/**
38
* Response containing metric data
39
*/
40
public static final class MetricDescriptor {
41
public String getName();
42
public String getDescription();
43
public String getBaseUnit();
44
public List<Sample> getMeasurements();
45
public List<AvailableTag> getAvailableTags();
46
47
public static final class Sample {
48
public String getStatistic();
49
public Double getValue();
50
}
51
52
public static final class AvailableTag {
53
public String getTag();
54
public Set<String> getValues();
55
}
56
}
57
}
58
```
59
60
### Auto Timer Configuration
61
62
Automatic timing configuration for HTTP requests and method executions.
63
64
```java { .api }
65
/**
66
* Configuration for automatic timer creation
67
*/
68
public final class AutoTimer {
69
public static final AutoTimer ENABLED = new AutoTimer(true);
70
public static final AutoTimer DISABLED = new AutoTimer(false);
71
72
public AutoTimer(boolean enabled);
73
public AutoTimer(boolean enabled, AutoTimerProperties properties);
74
75
public boolean isEnabled();
76
public Duration[] getPercentilesHistogram();
77
public Duration getExpectedMax();
78
public Duration getExpectedMin();
79
80
/**
81
* Properties for auto timer configuration
82
*/
83
public static class AutoTimerProperties {
84
public Duration[] getPercentilesHistogram();
85
public void setPercentilesHistogram(Duration[] percentilesHistogram);
86
87
public Duration getExpectedMax();
88
public void setExpectedMax(Duration expectedMax);
89
90
public Duration getExpectedMin();
91
public void setExpectedMin(Duration expectedMin);
92
}
93
}
94
```
95
96
### Cache Metrics
97
98
Metrics binders for various caching implementations.
99
100
```java { .api }
101
/**
102
* Generic cache metrics binder
103
*/
104
public class CacheMetrics implements MeterBinder {
105
public static <C> CacheMetrics monitor(MeterRegistry registry, C cache, String cacheName, String... tags);
106
public static <C> CacheMetrics monitor(MeterRegistry registry, C cache, String cacheName, Iterable<Tag> tags);
107
108
@Override
109
public void bindTo(MeterRegistry registry);
110
}
111
112
/**
113
* Caffeine cache metrics binder
114
*/
115
public class CaffeineMetrics implements MeterBinder {
116
public static CaffeineMetrics monitor(MeterRegistry registry, com.github.benmanes.caffeine.cache.Cache<?, ?> cache, String cacheName, String... tags);
117
118
@Override
119
public void bindTo(MeterRegistry registry);
120
}
121
122
/**
123
* Hazelcast cache metrics binder
124
*/
125
public class HazelcastCacheMetrics implements MeterBinder {
126
public static HazelcastCacheMetrics monitor(MeterRegistry registry, HazelcastInstance hazelcastInstance, String... tags);
127
128
@Override
129
public void bindTo(MeterRegistry registry);
130
}
131
132
/**
133
* JCache (JSR-107) metrics binder
134
*/
135
public class JCacheMetrics implements MeterBinder {
136
public static JCacheMetrics monitor(MeterRegistry registry, javax.cache.Cache<?, ?> cache, String... tags);
137
138
@Override
139
public void bindTo(MeterRegistry registry);
140
}
141
142
/**
143
* Redis cache metrics binder
144
*/
145
public class RedisCacheMetrics implements MeterBinder {
146
public static RedisCacheMetrics monitor(MeterRegistry registry, RedisCacheManager cacheManager, String... tags);
147
148
@Override
149
public void bindTo(MeterRegistry registry);
150
}
151
152
/**
153
* Cache2k metrics binder
154
*/
155
public class Cache2kMetrics implements MeterBinder {
156
public static Cache2kMetrics monitor(MeterRegistry registry, org.cache2k.Cache<?, ?> cache, String... tags);
157
158
@Override
159
public void bindTo(MeterRegistry registry);
160
}
161
```
162
163
**Usage Example:**
164
165
```java
166
@Configuration
167
public class CacheMetricsConfiguration {
168
169
@Bean
170
public MeterBinder caffeineMetrics(CacheManager cacheManager, MeterRegistry meterRegistry) {
171
if (cacheManager instanceof CaffeineCacheManager) {
172
CaffeineCacheManager caffeineCacheManager = (CaffeineCacheManager) cacheManager;
173
// Monitor all caches
174
caffeineCacheManager.getCacheNames().forEach(cacheName -> {
175
Cache cache = caffeineCacheManager.getCache(cacheName);
176
if (cache.getNativeCache() instanceof com.github.benmanes.caffeine.cache.Cache) {
177
CaffeineMetrics.monitor(meterRegistry,
178
(com.github.benmanes.caffeine.cache.Cache<?, ?>) cache.getNativeCache(),
179
cacheName);
180
}
181
});
182
}
183
return registry -> {}; // Empty binder as monitoring is already set up
184
}
185
}
186
```
187
188
### Database Connection Pool Metrics
189
190
Metrics for database connection pools.
191
192
```java { .api }
193
/**
194
* Generic data source pool metrics binder
195
*/
196
public class DataSourcePoolMetrics implements MeterBinder {
197
public static DataSourcePoolMetrics monitor(MeterRegistry registry, DataSource dataSource, String dataSourceName, String... tags);
198
199
@Override
200
public void bindTo(MeterRegistry registry);
201
}
202
203
/**
204
* Generic connection pool metrics
205
*/
206
public class ConnectionPoolMetrics implements MeterBinder {
207
public ConnectionPoolMetrics(String poolName, String... tags);
208
public ConnectionPoolMetrics(String poolName, Iterable<Tag> tags);
209
210
@Override
211
public void bindTo(MeterRegistry registry);
212
}
213
214
/**
215
* HikariCP connection pool metrics binder
216
*/
217
public class HikariDataSourcePoolMetrics implements MeterBinder {
218
public static HikariDataSourcePoolMetrics monitor(MeterRegistry registry, HikariDataSource hikariDataSource, String dataSourceName, String... tags);
219
220
@Override
221
public void bindTo(MeterRegistry registry);
222
}
223
```
224
225
**Usage Example:**
226
227
```java
228
@Configuration
229
public class DataSourceMetricsConfiguration {
230
231
@Bean
232
public MeterBinder hikariMetrics(DataSource dataSource, MeterRegistry meterRegistry) {
233
if (dataSource instanceof HikariDataSource) {
234
return HikariDataSourcePoolMetrics.monitor(meterRegistry,
235
(HikariDataSource) dataSource,
236
"primary");
237
}
238
return DataSourcePoolMetrics.monitor(meterRegistry, dataSource, "primary");
239
}
240
}
241
```
242
243
### HTTP Client Metrics
244
245
Metrics for HTTP client requests.
246
247
```java { .api }
248
/**
249
* RestTemplate metrics binder
250
*/
251
public class RestTemplateMetrics implements MeterBinder {
252
public static RestTemplateMetrics monitor(MeterRegistry registry, RestTemplate restTemplate, String... tags);
253
254
@Override
255
public void bindTo(MeterRegistry registry);
256
}
257
258
/**
259
* WebClient metrics binder
260
*/
261
public class WebClientMetrics implements MeterBinder {
262
public static WebClientMetrics monitor(MeterRegistry registry, WebClient webClient, String... tags);
263
264
@Override
265
public void bindTo(MeterRegistry registry);
266
}
267
```
268
269
**Usage Example:**
270
271
```java
272
@Configuration
273
public class HttpClientMetricsConfiguration {
274
275
@Bean
276
public RestTemplate restTemplate(MeterRegistry meterRegistry) {
277
RestTemplate restTemplate = new RestTemplate();
278
RestTemplateMetrics.monitor(meterRegistry, restTemplate, "external-api");
279
return restTemplate;
280
}
281
282
@Bean
283
public WebClient webClient(MeterRegistry meterRegistry) {
284
WebClient webClient = WebClient.builder()
285
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(2 * 1024 * 1024))
286
.build();
287
WebClientMetrics.monitor(meterRegistry, webClient, "reactive-api");
288
return webClient;
289
}
290
}
291
```
292
293
### Server Metrics
294
295
Metrics for embedded servers.
296
297
```java { .api }
298
/**
299
* Tomcat server metrics binder
300
*/
301
public class TomcatMetrics implements MeterBinder {
302
public static TomcatMetrics monitor(MeterRegistry registry, Tomcat tomcat, String... tags);
303
public static TomcatMetrics monitorThreadPool(MeterRegistry registry, ThreadPoolExecutor threadPoolExecutor, String... tags);
304
305
@Override
306
public void bindTo(MeterRegistry registry);
307
}
308
309
/**
310
* Jetty server metrics binder
311
*/
312
public class JettyMetrics implements MeterBinder {
313
public static JettyMetrics monitor(MeterRegistry registry, Server server, String... tags);
314
public static JettyMetrics monitor(MeterRegistry registry, QueuedThreadPool threadPool, String... tags);
315
316
@Override
317
public void bindTo(MeterRegistry registry);
318
}
319
```
320
321
### Prometheus Integration
322
323
Special endpoint and manager for Prometheus metrics export.
324
325
```java { .api }
326
/**
327
* Endpoint for Prometheus scraping
328
*/
329
@Endpoint(id = "prometheus")
330
public class PrometheusScrapeEndpoint {
331
public PrometheusScrapeEndpoint(CollectorRegistry collectorRegistry);
332
333
@ReadOperation(produces = "text/plain")
334
public String scrape();
335
}
336
337
/**
338
* Manager for Prometheus push gateway integration
339
*/
340
public class PrometheusPushGatewayManager {
341
public PrometheusPushGatewayManager(PushGateway pushGateway,
342
CollectorRegistry collectorRegistry,
343
Duration pushRate,
344
String job);
345
346
public void start();
347
public void stop();
348
public boolean isRunning();
349
}
350
```
351
352
**Usage Example:**
353
354
```java
355
@Configuration
356
@ConditionalOnClass(PrometheusMeterRegistry.class)
357
public class PrometheusConfiguration {
358
359
@Bean
360
public PrometheusScrapeEndpoint prometheusScrapeEndpoint(CollectorRegistry collectorRegistry) {
361
return new PrometheusScrapeEndpoint(collectorRegistry);
362
}
363
364
@Bean
365
@ConditionalOnProperty(name = "management.metrics.export.prometheus.pushgateway.enabled", havingValue = "true")
366
public PrometheusPushGatewayManager prometheusPushGatewayManager(
367
PushGateway pushGateway,
368
CollectorRegistry collectorRegistry,
369
@Value("${management.metrics.export.prometheus.pushgateway.push-rate:PT30S}") Duration pushRate,
370
@Value("${management.metrics.export.prometheus.pushgateway.job:spring-boot-app}") String job) {
371
return new PrometheusPushGatewayManager(pushGateway, collectorRegistry, pushRate, job);
372
}
373
}
374
```
375
376
### Custom Metrics
377
378
Integration with Micrometer for custom metrics.
379
380
```java { .api }
381
// Note: These are Micrometer interfaces, but commonly used with Actuator
382
383
/**
384
* Registry for meters
385
*/
386
public interface MeterRegistry extends io.micrometer.core.instrument.MeterRegistry {
387
// Core Micrometer interface for registering meters
388
}
389
390
/**
391
* Interface for binding meters to a registry
392
*/
393
public interface MeterBinder {
394
/**
395
* Bind meters to the given registry
396
*/
397
void bindTo(MeterRegistry registry);
398
}
399
```
400
401
**Usage Example:**
402
403
```java
404
@Component
405
public class CustomMetrics implements MeterBinder {
406
407
private final Counter orderCounter;
408
private final Timer orderProcessingTimer;
409
private final Gauge activeOrdersGauge;
410
private final AtomicInteger activeOrders = new AtomicInteger(0);
411
412
public CustomMetrics(MeterRegistry meterRegistry) {
413
this.orderCounter = Counter.builder("orders.processed")
414
.description("Total number of processed orders")
415
.tag("type", "online")
416
.register(meterRegistry);
417
418
this.orderProcessingTimer = Timer.builder("orders.processing.time")
419
.description("Order processing time")
420
.register(meterRegistry);
421
422
this.activeOrdersGauge = Gauge.builder("orders.active")
423
.description("Currently active orders")
424
.register(meterRegistry, activeOrders, AtomicInteger::get);
425
}
426
427
@Override
428
public void bindTo(MeterRegistry registry) {
429
// Custom meters are already registered in constructor
430
// This method can be used for additional meters if needed
431
}
432
433
public void recordOrderProcessed() {
434
orderCounter.increment();
435
}
436
437
public void recordOrderProcessingTime(Duration duration) {
438
orderProcessingTimer.record(duration);
439
}
440
441
public void incrementActiveOrders() {
442
activeOrders.incrementAndGet();
443
}
444
445
public void decrementActiveOrders() {
446
activeOrders.decrementAndGet();
447
}
448
}
449
```