Spring Boot 2.x 自定义metrics 并导出到influxdb
Step 1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-influx</artifactId>
</dependency>
Step 2.修改Spring配置文件application.yml
management:
endpoints:
enabled-by-default: true
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
metrics:
export:
influx:
enabled: true
db: spring
uri: http://localhost:8086
step: 10s
user-name: admin
password: admin
Step 3. 实现micrometer的MeterBinder接口
public class DemoMetrics implements MeterBinder {
AtomicInteger count = new AtomicInteger(0); @Override
public void bindTo(MeterRegistry meterRegistry) {
Gauge.builder("demo.count", count, c -> c.incrementAndGet())
.tags("host", "localhost")
.description("demo of custom meter binder")
.register(meterRegistry);
}
这里实现了MeterBinder接口的bindTo方法,将要采集的指标注册到MeterRegistry
Step 4.注册
@Bean
public DemoMetrics demoMetrics(){
return new DemoMetrics();
}
在springboot只要标注下bean,注入到spring容器后,springboot会自动注册到registry。springboot已经帮你初始化了包括UptimeMetrics等一系列metrics。
源码解析
MetricsAutoConfiguration
spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MetricsAutoConfiguration.java
@Configuration
@ConditionalOnClass(Timed.class)
@EnableConfigurationProperties(MetricsProperties.class)
@AutoConfigureBefore(CompositeMeterRegistryAutoConfiguration.class)
public class MetricsAutoConfiguration { @Bean
@ConditionalOnMissingBean
public Clock micrometerClock() {
return Clock.SYSTEM;
} @Bean
public static MeterRegistryPostProcessor meterRegistryPostProcessor(
ApplicationContext context) {
return new MeterRegistryPostProcessor(context);
} @Bean
@Order(0)
public PropertiesMeterFilter propertiesMeterFilter(MetricsProperties properties) {
return new PropertiesMeterFilter(properties);
} @Configuration
@ConditionalOnProperty(value = "management.metrics.binders.jvm.enabled", matchIfMissing = true)
static class JvmMeterBindersConfiguration { @Bean
@ConditionalOnMissingBean
public JvmGcMetrics jvmGcMetrics() {
return new JvmGcMetrics();
} @Bean
@ConditionalOnMissingBean
public JvmMemoryMetrics jvmMemoryMetrics() {
return new JvmMemoryMetrics();
} @Bean
@ConditionalOnMissingBean
public JvmThreadMetrics jvmThreadMetrics() {
return new JvmThreadMetrics();
} @Bean
@ConditionalOnMissingBean
public ClassLoaderMetrics classLoaderMetrics() {
return new ClassLoaderMetrics();
} } @Configuration
static class MeterBindersConfiguration { @Bean
@ConditionalOnClass(name = { "ch.qos.logback.classic.LoggerContext",
"org.slf4j.LoggerFactory" })
@Conditional(LogbackLoggingCondition.class)
@ConditionalOnMissingBean(LogbackMetrics.class)
@ConditionalOnProperty(value = "management.metrics.binders.logback.enabled", matchIfMissing = true)
public LogbackMetrics logbackMetrics() {
return new LogbackMetrics();
} @Bean
@ConditionalOnProperty(value = "management.metrics.binders.uptime.enabled", matchIfMissing = true)
@ConditionalOnMissingBean
public UptimeMetrics uptimeMetrics() {
return new UptimeMetrics();
} @Bean
@ConditionalOnProperty(value = "management.metrics.binders.processor.enabled", matchIfMissing = true)
@ConditionalOnMissingBean
public ProcessorMetrics processorMetrics() {
return new ProcessorMetrics();
} @Bean
@ConditionalOnProperty(name = "management.metrics.binders.files.enabled", matchIfMissing = true)
@ConditionalOnMissingBean
public FileDescriptorMetrics fileDescriptorMetrics() {
return new FileDescriptorMetrics();
} } static class LogbackLoggingCondition extends SpringBootCondition { @Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
ConditionMessage.Builder message = ConditionMessage
.forCondition("LogbackLoggingCondition");
if (loggerFactory instanceof LoggerContext) {
return ConditionOutcome.match(
message.because("ILoggerFactory is a Logback LoggerContext"));
}
return ConditionOutcome
.noMatch(message.because("ILoggerFactory is an instance of "
+ loggerFactory.getClass().getCanonicalName()));
} } }
可以看到这里注册了好多metrics,比如UptimeMetrics,JvmGcMetrics,ProcessorMetrics,FileDescriptorMetrics等
这里重点看使用@Bean标注了MeterRegistryPostProcessor
MeterRegistryPostProcessor
spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryPostProcessor.java
class MeterRegistryPostProcessor implements BeanPostProcessor { private final ApplicationContext context; private volatile MeterRegistryConfigurer configurer; MeterRegistryPostProcessor(ApplicationContext context) {
this.context = context;
} @Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof MeterRegistry) {
getConfigurer().configure((MeterRegistry) bean);
}
return bean;
} @SuppressWarnings("unchecked")
private MeterRegistryConfigurer getConfigurer() {
if (this.configurer == null) {
this.configurer = new MeterRegistryConfigurer(beansOfType(MeterBinder.class),
beansOfType(MeterFilter.class),
(Collection<MeterRegistryCustomizer<?>>) (Object) beansOfType(
MeterRegistryCustomizer.class),
this.context.getBean(MetricsProperties.class).isUseGlobalRegistry());
}
return this.configurer;
} private <T> Collection<T> beansOfType(Class<T> type) {
return this.context.getBeansOfType(type).values();
} }
可以看到这里new了一个MeterRegistryConfigurer,重点注意这里使用beansOfType(MeterBinder.class)方法的返回值给其构造器
MeterRegistryConfigurer
spring-boot-actuator-autoconfigure-2.0.0.RELEASE-sources.jar!/org/springframework/boot/actuate/autoconfigure/metrics/MeterRegistryConfigurer.java
class MeterRegistryConfigurer { private final Collection<MeterRegistryCustomizer<?>> customizers; private final Collection<MeterFilter> filters; private final Collection<MeterBinder> binders; private final boolean addToGlobalRegistry; MeterRegistryConfigurer(Collection<MeterBinder> binders,
Collection<MeterFilter> filters,
Collection<MeterRegistryCustomizer<?>> customizers,
boolean addToGlobalRegistry) {
this.binders = (binders != null ? binders : Collections.emptyList());
this.filters = (filters != null ? filters : Collections.emptyList());
this.customizers = (customizers != null ? customizers : Collections.emptyList());
this.addToGlobalRegistry = addToGlobalRegistry;
} void configure(MeterRegistry registry) {
if (registry instanceof CompositeMeterRegistry) {
return;
}
// Customizers must be applied before binders, as they may add custom
// tags or alter timer or summary configuration.
customize(registry);
addFilters(registry);
addBinders(registry);
if (this.addToGlobalRegistry && registry != Metrics.globalRegistry) {
Metrics.addRegistry(registry);
}
} @SuppressWarnings("unchecked")
private void customize(MeterRegistry registry) {
LambdaSafe.callbacks(MeterRegistryCustomizer.class, this.customizers, registry)
.withLogger(MeterRegistryConfigurer.class)
.invoke((customizer) -> customizer.customize(registry));
} private void addFilters(MeterRegistry registry) {
this.filters.forEach(registry.config()::meterFilter);
} private void addBinders(MeterRegistry registry) {
this.binders.forEach((binder) -> binder.bindTo(registry));
} }
可以看到configure方法里头调用了addBinders,也就是把托管给spring容器的MeterBinder实例bindTo到meterRegistry
Spring Boot 2.x 自定义metrics 并导出到influxdb的更多相关文章
- spring boot / cloud (四) 自定义线程池以及异步处理@Async
spring boot / cloud (四) 自定义线程池以及异步处理@Async 前言 什么是线程池? 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线 ...
- Spring boot 自动配置自定义配置文件
示例如下: 1. 新建 Maven 项目 properties 2. pom.xml <project xmlns="http://maven.apache.org/POM/4 ...
- 如何优雅地在 Spring Boot 中使用自定义注解,AOP 切面统一打印出入参日志 | 修订版
欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 个人网站: https://www.ex ...
- Spring Boot 中关于自定义异常处理的套路!
在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @ControllerAdvice 来统一处理,也可以自己来定义异常处理方案.Spring Boot 中,对异常的处理有 ...
- Spring Boot笔记之自定义启动banner
控制banner内容 Spring Boot启动的时候默认的banner是spring的字样,看多了觉得挺单调的,Spring Boot为我们提供了自定义banner的功能. 自定义banner只需要 ...
- Spring boot JPA 用自定义主键策略 生成自定义主键ID
最近学习Spring boot JPA 学习过程解决的一些问题写成随笔,大家一起成长.这次遇到自定义主键的问题 package javax.persistence; public enum Gener ...
- 20. Spring Boot 默认、自定义数据源 、配置多个数据源 jdbcTemplate操作DB
Spring-Boot-2.0.0-M1版本将默认的数据库连接池从tomcat jdbc pool改为了hikari,这里主要研究下hikari的默认配置 0. 创建Spring Boot项目,选中 ...
- Spring Boot中的自定义start pom
start pom是springboot中提供的简化企业级开发绝大多数场景的一个工具,利用好strat pom就可以消除相关技术的配置得到自动配置好的Bean. 举个例子,在一般使用中,我们使用基本的 ...
- Spring Boot环境下自定义shiro过滤器会过滤所有的url的问题
在配置shiro过滤器时增加了自定义的过滤器,主要是用来处理未登录状态下返回一些信息 //自定义过滤器 Map<String, Filter> filtersMap = new Linke ...
随机推荐
- UIViewController+MJPopupViewController
1.MJPopupBackgroundView 1.1 MJPopupBackgroundView.h // // MJPopupBackgroundView.h // watched // // C ...
- VB6加载MSCOMCTL.OCX出现“不能加载''”错误的处理方法汇总
自从我安装卸载几次OFFICE和WPS后,VB6就出现了这样的问题. 然后在网上收集各种解决办法: 1.第一种:工程文件引用可能有问题,跟本机的相关组件版本不一致. 用记事本打开VBP文件找到这一行: ...
- css入门知识点整理
css入门知识点整理 不要嘲笑我这个蒟蒻..例子来源:w3school css其实就分为两个东西,一个是选择器,另外一个是声明.声明定义了某个对象的属性的值,这都是html的内容.重点要关注的是选择器 ...
- Internet路由-主机路由表和转发表
1.路由表 路由信息最终要存储在用于路由器的主机或者专业路由器上,存放这些信息的地方称为路由表.其中包含三元素:目标地址,掩码,下一跳. 1.1.查询路由表的开销 有人认为查询路由表是一件和交换机查询 ...
- P4449 于神之怒加强版
\(\color{#0066ff}{ 题目描述 }\) 给定n,m,k,计算 \(\sum_{i=1}^n \sum_{j=1}^m \mathrm{gcd}(i,j)^k\) 对1000000007 ...
- node mysql问题:Client does not support authentication protocol requested by server; consider upgrading MySQL client!
node后台 mysql处理模块(版本:2.16.0) 执行connect方法时报错: Client does not support authentication protocol requeste ...
- 使用git将本地代码提交到码云上去
码云为开源中国基于git的代码网络托管平台,将代码托管.开发与项目管理工具融为一体.今天第一次将自己的web项目代码上传至码云,过程中遇到一些问题,此处进行总结与过程的演示:当我们在码云上创建好项目后 ...
- angularJs实现修改功能
思路: 对表单中内容进行修改,首先需要获取这个内容,再进行修改,再清空弹窗中的内容 //查询实体 $scope.findOne=function(id){ $http.get('../brand/fi ...
- DRF教程7-token认证
Authentication 认证是将一个传入的请求和一组标识凭据相关联的机制,比如请求过来的用户,或者用户登录时携带的token. 然后权限策略就能使用这些凭据来决定是否允许这个请求. REST框架 ...
- 【Groovy】Spock with Maven
已经在项目里使用Groovy/Spock做测试框架了,感觉和Maven结合在一起还是挺好用的. 在Maven的pom.xml里引入他们还是挺方便的,第一先要在dependency 里引入 <de ...