文档章节

prometheus收集springboot指标

super-wen
 super-wen
发布于 2017/06/02 17:53
字数 577
阅读 172
收藏 3

##prometheus 主动采集 springboot

maven dependency

          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-actuator</artifactId>
                <version>${spring-boot.version}</version>
         </dependency>

        <dependency>
            <groupId>com.moelholm</groupId>
            <artifactId>prometheus-spring-boot-starter</artifactId>
            <version>1.0.1</version>
        </dependency>

实现逻辑

将springboot内部的publicMetrics转为prometheus 格式.

@Component
public class SpringBootMetricsCollector extends Collector {
  private final Collection<PublicMetrics> publicMetrics;

  @Autowired
  public SpringBootMetricsCollector(Collection<PublicMetrics> publicMetrics) {
    this.publicMetrics = publicMetrics;
  }

  @Override
  public List<MetricFamilySamples> collect() {
    ArrayList<MetricFamilySamples> samples = new ArrayList<MetricFamilySamples>();
    for (PublicMetrics publicMetrics : this.publicMetrics) {
      for (Metric<?> metric : publicMetrics.metrics()) {
        String name = Collector.sanitizeMetricName(metric.getName());
        double value = metric.getValue().doubleValue();
        MetricFamilySamples metricFamilySamples = new MetricFamilySamples(
                name, Type.GAUGE, name, Collections.singletonList(
                new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), value)));
        samples.add(metricFamilySamples);
      }
    }
    return samples;
  }
}

prometheus 通过访问/prometheus节点采集。

git库地址:https://github.com/thomasdarimont/prometheus-spring-boot-starter

springboot 推送metrics 到 pushGateway,然后prometheus 去pushGateway采集。

          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-actuator</artifactId>
                <version>${spring-boot.version}</version>
         </dependency>

            <dependency>
                <groupId>io.prometheus</groupId>
                <artifactId>simpleclient_pushgateway</artifactId>
                <version>0.0.21</version>
            </dependency>
             <dependency>
                <groupId>io.prometheus</groupId>
                <artifactId>simpleclient_spring_boot</artifactId>
                <version>0.0.21</version>
            </dependency>
            

具体代码

@Configuration
@ComponentScan("io.prometheus.client.spring.boot")
public class PrometheusConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusConfiguration.class);

    @Value("${spring.application.name}")
    String applicationName;

    @Value("${prometheus.pushgateway.host}")
    String pushHost;

    @Value("${prometheus.pushgateway.intervalInMillis:10000}")
    long intervalInMillis;


    @Autowired
    private SpringBootMetricsCollector springBootMetricsCollector;


    @PostConstruct
    public void initialize() {
        Map<String,String> map = new HashMap<>();
        //这里存在问题,在docker中获得的是1@localhost
        map.put("instance", ManagementFactory.getRuntimeMXBean().getName());
        PushGateway prometheusPush = new PushGateway(pushHost);
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                LOGGER.debug("prometheus push");
                prometheusPush.push(springBootMetricsCollector, applicationName,map);
            } catch (Exception e) {
                LOGGER.error("prometheus push error", e);
            }
        }, 5000, intervalInMillis, TimeUnit.MILLISECONDS);
    }
}

修改上述代码,使之适用dcos,docker环境

当服务部署在dcos上时,端口是不固定,数量是不固定的.这时候就需要通过主动推送到pushGateway后,交由prometheus 采集.

@Configuration
public class SystemConfiguration implements EnvironmentAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(SystemConfiguration.class);

    private String host;//docker 传入的宿主机ip

    private String port0;

    private String prot1;

    @Value("${server.port}")
    private String serverPort;

    @Override
    public void setEnvironment(Environment environment) {
        /**
         * 在docker中.目的是从环境变量中获得传入的宿主机ip和端口.
         */
        this.host = environment.getProperty("HOST");
        this.port0 = environment.getProperty("PORT0");
        this.prot1 = environment.getProperty("PORT1");
        LOGGER.info("-------------------------environment");
        LOGGER.info("host:"+host);
        LOGGER.info("port0:"+ port0);
        LOGGER.info("prot1:"+ prot1);
    }

    @PostConstruct
    public void init(){
        if(StringUtils.isEmpty(host)){
            //未能从环境变量中获得host
            try {
                 this.host = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                LOGGER.error("获得host失败",e);
            }
            this.port0 = serverPort;
        }
        LOGGER.info("-------------------------postConstruct");
        LOGGER.info("host:"+this.host);
        LOGGER.info("port0:"+this.port0);
    }


    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort0() {
        return port0;
    }

    public void setPort0(String port0) {
        this.port0 = port0;
    }

    public String getProt1() {
        return prot1;
    }

    public void setProt1(String prot1) {
        this.prot1 = prot1;
    }

    public String getServerPort() {
        return serverPort;
    }

    public void setServerPort(String serverPort) {
        this.serverPort = serverPort;
    }
}

@Configuration
@ComponentScan("io.prometheus.client.spring.boot")
public class PrometheusConfiguration  {
    private static final Logger LOGGER = LoggerFactory.getLogger(PrometheusConfiguration.class);

    @Value("${spring.application.name}")
    String applicationName;

    @Value("${prometheus.pushgateway.host}")
    String pushHost;

    @Value("${prometheus.pushgateway.intervalInMillis:10000}")
    long intervalInMillis;

    @Autowired
    private SystemConfiguration systemConfiguration;


    @Autowired
    private SpringBootMetricsCollector springBootMetricsCollector;


    @PostConstruct
    public void initialize() {


        Map<String,String> map = new HashMap<>();
        map.put("instance", systemConfiguration.getHost()+"@"+systemConfiguration.getPort0());
        PushGateway prometheusPush = new PushGateway(pushHost);
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                LOGGER.debug("prometheus push");
                prometheusPush.push(springBootMetricsCollector, applicationName,map);
            } catch (Exception e) {
                LOGGER.error("prometheus push error", e);
            }
        }, 5000, intervalInMillis, TimeUnit.MILLISECONDS);
    }


}

© 著作权归作者所有

共有 人打赏支持
super-wen
粉丝 5
博文 36
码字总数 12956
作品 0
徐汇
程序员
为springboot项目添加springboot-admin监控

我们知道spring-boot-actuator暴露了大量统计和监控信息的端点,spring-boot-admin 就是为此提供的监控项目。 先来看看大概会提供什么样的功能 从图中可以看出,主要内容都是由spring boot a...

ryan-miao
06/12
0
0
springboot2输出metrics到influxdb

序 本文主要研究一下如何将springboot2的metrics输出到influxdb maven 配置 influx 启动之后创建数据库 命令行创建 rest接口创建 返回 或者直接配置文件指定auto-create-db=true,就无需额外...

go4it
06/17
0
0
SpringBoot-01:什么是SpringBoot?

------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- SpringBoot: Spring Boot可以轻松创建独立的,生产级的基于Spring的应用程序,您可以“运行”。 SpringBoot对Spring平台和...

晨曦dawn
06/22
0
0
深入理解SpringBoot的过滤条件--AutoConfigure

我们知道在Spring及SpringBoot里按条件创建Bean的核心是接口与注解,其实在SpringBoot里还有一种AutoConfigure也可以来过滤配置,只不过这种技术,能够让SpringBoot更快速的启动,那么下面我们...

融科聂晨
07/23
0
0
SpringBoot学习之基础篇

在前面的博文中,已经演示过springboot与Mybatis集成的实例,本篇再来探讨一下SpringBoot的基础。 一。关于SpringBoot   SpringBoot可以基于Spring轻松创建可以“运行”的、独立的、生产级...

java~nick
2017/10/31
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

jetbrains系产品IDEA:mac上面提示快捷键设置

原因 由于Mac上面的Ctrl+空格变成输入法切换的快捷键,在使用IDEA的过程中,代码提示很不方便,需要使用option+/这种传统eclipse上面的代码提示快捷键作为主要快捷键。 怎么修改? 移除【opt...

亚林瓜子
33分钟前
0
0
Exclipse 输出结果时换行

System.out.println(f1 + "\n" + d1 + "\n" + d2);

笑丶笑
34分钟前
1
0
怎样治疗标签不能触发onblur事件

I realize this was over a year ago, but it showed up for me in Google while trying to solve this same issue. It seems Chrome does not consider some elements, like body and ancho......

Weijuer
37分钟前
0
0
vue常见库安装

移动设备上的浏览器默认会在用户点击屏幕大约延迟300毫秒后才会触发点击事件,这是为了检查用户是否在做双击。为了能够立即响应用户的点击事件,才有了FastClick。 安装fastclick npm insta...

林夏夕
39分钟前
0
0
kafka 教程(三) kafka Java API 编程

下午写

MrPei
40分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部