Spring boot 在项目中的应用-监控(三)

2018-08-06  本文已影响0人  咦咦咦萨

基本流程: Spring boot 暴露统计端点,Prometheus采集处理,Grafana提供展示界面。

1. 添加依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
      <groupId>io.prometheus</groupId>
      <artifactId>simpleclient_spring_boot</artifactId>
      <version>0.0.26</version>
    </dependency>

2. 配置application.yml

security:
  basic:
    # 启用基础认证
    enabled: false
    # 安全路径列表,逗号分隔,此处只针对/admin路径进行认证
    path: /admin
  user:
    # 认证使用的用户名
    name: admin
    # 认证使用的密码。 默认情况下,启动时会记录随机密码。
    password: 123456

management:
  # actuator暴露接口使用的端口,为了和api接口使用的端口进行分离
  port: 7778
  # actuator暴露接口的前缀
  context-path: /admin
  security:
    # actuator是否需要安全保证
    enabled: true
    # 可以访问管理端点的用户角色列表,逗号分隔
    roles: SUPERUSER

endpoints:
  metrics:
    # actuator的metrics接口是否开启
    enabled: true
    # actuator的metrics接口是否需要安全保证
    sensitive: false
  health:
    # actuator的health接口是否开启
    enabled: true
    # actuator的health接口是否需要安全保证
    sensitive: false
  #启用shutdown
  shutdown:
    enabled: true

3. 通过注释实现自定义Prometheus统计指标

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PrometheusMetrics {

    /**
     * 默认为空,程序使用method signature作为Metric name
     * 如果name有设置值,使用name作为Metric name
     */
    String name() default "";
}
@Aspect
@Component
@Slf4j
public class PrometheusMetricsAspect {
    private static final Counter requestTotal = Counter.build().name("couter_all").labelNames("api").help
        ("total request couter of api").register();
    private static final Counter requestError = Counter.build().name("couter_error").labelNames("api").help
        ("response Error couter of api").register();
    private static final Histogram histogram = Histogram.build().name("histogram_consuming").labelNames("api").help
        ("response consuming of api").register();

    /**
     * 自定义Prometheus注解的全路径
     */
    @Pointcut("@annotation(com.test.PrometheusMetrics)")
    public void pcMethod() {

    }

    @Around(value="pcMethod() && @annotation(annotation)")
    public Object metricsCollector(ProceedingJoinPoint joinPoint, PrometheusMetrics annotation) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        PrometheusMetrics prometheusMetrics = methodSignature.getMethod()
            .getAnnotation(PrometheusMetrics.class);
        if (null == prometheusMetrics) {
            return joinPoint.proceed();
        }
        String name;
        if (StringUtils.isNotEmpty(prometheusMetrics.name())) {
            name = prometheusMetrics.name();
        } else {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes())
                .getRequest();
            name = request.getRequestURI();
        }
        requestTotal.labels(name).inc();
        Histogram.Timer requestTimer = histogram.labels(name).startTimer();
        Object object;
        try {
            object = joinPoint.proceed();
        } catch (Exception e) {
            requestError.labels(name).inc();
            throw e;
        } finally {
            requestTimer.observeDuration();
        }
        return object;
    }
}

使用方法:


image.png

访问/sign后,会自动生成counter_status_200_sign,counter_all等指标

4. docker部署Prometheus

docker pull prom/prometheus
global:
  scrape_interval: 10s
  scrape_timeout: 10s
  evaluation_interval: 10m
scrape_configs:
  - job_name: spring-boot
    scrape_interval: 5s
    scrape_timeout: 5s
    metrics_path: /admin/prometheus
    scheme: http
    basic_auth:
      # 对应application.yml security配置
      username: admin
      password: 123456
    static_configs:
      - targets:
        - 127.0.0.1:7778
docker run -d \
--name prometheus \
-p 10000:9090 \
-m 500M \
-v "$(pwd)/prometheus.yml":/etc/prometheus/prometheus.yml \
-v "$(pwd)/data":/data \
prom/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--log.level=info

解决办法就是把-config.file和-log.level前加一个‘-’,--config和--log。
参见:https://github.com/prometheus/prometheus/issues/2878

image.png

5. docker安装Grafana

docker pull grafana/grafana
docker run -d --name=grafana -p 3000:3000 grafana/grafana

扩展:
Prometheus指标类型:http://licyhust.com/%E5%AE%B9%E5%99%A8%E6%8A%80%E6%9C%AF/2017/07/10/prometheus-metrics/

参考:
https://blog.csdn.net/fly910905/article/details/78618969

上一篇 下一篇

猜你喜欢

热点阅读