All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.metric.JMetricContext Maven / Gradle / Ivy

/*--------------------------------------------------------------------------
 *  Copyright (c) 2010-2020, Elon.su All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the elon developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: Elon.su, you can also mail [email protected]
 *--------------------------------------------------------------------------
 */
package com.github.dennisit.vplus.data.metric;

import com.github.dennisit.vplus.data.metric.collector.DefaultCollector;
import com.github.dennisit.vplus.data.metric.config.JMetricConfig;
import com.github.dennisit.vplus.data.metric.pipeline.LoggerPipeline;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Elon.su
 */
public class JMetricContext implements JMetricBean {

    private static final Logger LOG = LoggerFactory.getLogger(JMetricContext.class);

    /**
     * 配置入口
     */
    private JMetricConfig jMetricConfig;

    /**
     * 采集器
     */
    private List collectors;

    /**
     * 管道流
     */
    private List pipelines;

    /**
     * 定时守护线程
     */
    private ScheduledExecutorService scheduledExecutorService;

    /**
     * 监控上下文
     */
    public JMetricContext() {
        this(Lists.newArrayList(new LoggerPipeline()));
    }

    /**
     * 监控上下文
     * @param pipelines 数据管道
     */
    public JMetricContext(List pipelines) {
        this(Lists.newArrayList(new DefaultCollector()), pipelines);
    }

    /**
     * 监控上下文
     * @param collectors 采集器
     * @param pipelines 数据管道
     */
    public JMetricContext(List collectors, List pipelines) {
        this(JMetricConfig.DEFAULT(), collectors, pipelines);
    }

    /**
     * 监控上线文
     * @param jMetricConfig 配置
     * @param collectors 采集器
     * @param pipelines 数据管道
     */
    public JMetricContext(JMetricConfig jMetricConfig, List collectors, List pipelines){
        this.jMetricConfig = jMetricConfig;
        this.collectors = collectors;
        this.pipelines = pipelines;
    }

    public void addCollcetor(JMetricCollector collector){
        if(CollectionUtils.isNotEmpty(collectors)){
            collectors = Lists.newArrayList();
        }
        collectors.add(collector);
    }

    public void addCollcetor(List collectors){
        if(CollectionUtils.isNotEmpty(collectors)){
            collectors = Lists.newArrayList();
        }
        collectors.addAll(collectors);
    }

    public void addPipeline(JMetricPipeline pipeline){
        if(CollectionUtils.isNotEmpty(pipelines)){
            pipelines = Lists.newArrayList();
        }
        pipelines.add(pipeline);
    }

    public void addPipeline(List pipelines){
        if(CollectionUtils.isNotEmpty(pipelines)){
            pipelines = Lists.newArrayList();
        }
        pipelines.addAll(pipelines);
    }

    public void configure(JMetricConfig config){
        this.jMetricConfig = config;
    }


    /**
     * 被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
     * 初始化示例
     */
    public void initialized() {
        if(!jMetricConfig.isEnabled()){
            return;
        }
        scheduledExecutorService = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r, "JMetric-Scheduled-" + threadNumber.getAndIncrement());
                if (t.isDaemon())
                    t.setDaemon(false);
                if (t.getPriority() != Thread.NORM_PRIORITY)
                    t.setPriority(Thread.NORM_PRIORITY);
                return t;
            }
        });

        final JMetricPipelineProxy proxy = new JMetricPipelineProxy();

        // 加载数据传输管道
        Optional.ofNullable(pipelines).orElse(Lists.newArrayList()).forEach(
                x -> {
                    x.initialized();
                    proxy.add(x);
                }
        );
        // 加载数据采集器
        Optional.ofNullable(collectors).orElse(Lists.newArrayList()).forEach(
                x -> {
                    x.initialized();
                }
        );

        scheduledExecutorService.scheduleAtFixedRate(()-> {
                LOG.info("管道推送:" + LocalDateTime.now(ZoneId.systemDefault()));
                Optional.ofNullable(collectors).orElse(Lists.newArrayList()).forEach(
                        x -> {
                            x.collect(proxy);
                        }
                );
        }, jMetricConfig.getInitialDelay(), jMetricConfig.getPeriodSeconds(), TimeUnit.SECONDS);
    }

    /**
     * 被@PreConstruct修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。
     * 销毁示例
     */
    //@PreDestroy
    public void destroyed() {
        // 销毁线程池
        if (null != scheduledExecutorService) {
            scheduledExecutorService.shutdownNow();
        }
        // 销毁采集器
        Optional.ofNullable(collectors).orElse(Lists.newArrayList()).forEach(
                x -> x.destroyed()
        );
        // 销毁数据传输管道
        Optional.ofNullable(pipelines).orElse(Lists.newArrayList()).forEach(
                x -> x.destroyed()
        );
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy