Spring集成Prometheus监控

1.配置拦截器

    <bean id="prometheusMetricsInterceptor" class="com.xxx.common.interceptor.PrometheusMetricsInterceptor" ></bean>
    <bean id="prometheusConfig" class="xxx" init-method="initialize" />

2.配置web.xml暴露监控指标

	<!-- 暴露服务监控指标 -->
	<servlet>
		<servlet-name>prometheus</servlet-name>
		<servlet-class>com.leopard.common.controller.PrometheusMetricsServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>prometheus</servlet-name>
		<url-pattern>/metrics</url-pattern>
	</servlet-mapping>

3.增加pom依赖

<!--普罗米修斯 -->
		<dependency>
			<groupId>io.prometheus</groupId>
			<artifactId>simpleclient</artifactId>
			<version>${prometheus.version}</version>
		</dependency>
		<!-- Hotspot JVM metrics-->
		<dependency>
			<groupId>io.prometheus</groupId>
			<artifactId>simpleclient_hotspot</artifactId>
			<version>${prometheus.version}</version>
		</dependency>
		<!-- Exposition servlet-->
		<dependency>
			<groupId>io.prometheus</groupId>
			<artifactId>simpleclient_servlet</artifactId>
			<version>${prometheus.version}</version>
		</dependency>
		<!-- Pushgateway exposition-->
		<dependency>
			<groupId>io.prometheus</groupId>
			<artifactId>simpleclient_pushgateway</artifactId>
			<version>${prometheus.version}</version>
		</dependency>
		<dependency>
			<groupId>io.prometheus</groupId>
			<artifactId>simpleclient_spring_web</artifactId>
			<version>${prometheus.version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-aop</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-context</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-web</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.aspectj</groupId>
					<artifactId>aspectjweaver</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.apache.commons</groupId>
					<artifactId>commons-lang3</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

4.编写配置类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;

public class PrometheusConfig {
    private static Logger log = LoggerFactory.getLogger(PrometheusConfig.class);

    @PostConstruct
    public void initialize() {
        DefaultExports.initialize();
    }

}
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.binder.cache.*;
import io.micrometer.core.instrument.binder.db.DatabaseTableMetrics;
import io.micrometer.core.instrument.binder.jetty.JettyServerThreadPoolMetrics;
import io.micrometer.core.instrument.binder.jvm.*;
import io.micrometer.core.instrument.binder.logging.LogbackMetrics;
import io.micrometer.core.instrument.binder.system.FileDescriptorMetrics;
import io.micrometer.core.instrument.binder.system.ProcessorMetrics;
import io.micrometer.core.instrument.binder.system.UptimeMetrics;
import io.micrometer.core.instrument.binder.tomcat.TomcatMetrics;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.micrometer.prometheus.PrometheusRenameFilter;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class PrometheusMetricsServlet extends HttpServlet {

    private static Logger log = LoggerFactory.getLogger(PrometheusMetricsServlet.class);

    private String appName = com.leopard.common.util.SystemConfig.getString("spring.application.name");

    private PrometheusMeterRegistry registry;
    private Set<MeterBinder> meterBinderSet = new HashSet<>();
    /**
     * 初始化指标注册器
     */
    @PostConstruct
    public void initRegistry() {
        PrometheusConfig prometheusConfig = PrometheusConfig.DEFAULT;
        CollectorRegistry defaultRegistry = CollectorRegistry.defaultRegistry;
        Clock clock = new MockClock();
        registry = new PrometheusMeterRegistry(prometheusConfig,defaultRegistry,clock);
        // 配置app名称
        registry.config().commonTags("application",appName);

        // 初始化监控指标
        initMetrics();

        // 指标绑定注册器
        meterBinderSet.forEach(meterBinder -> meterBinder.bindTo(registry));
    }

    /**
     * 初始化指标,按照项目需要进行配置,以下配置都是io.prometheus默认提供
     */
    private void initMetrics() {
        // jvm指标
        JvmGcMetrics jvmGcMetrics = new JvmGcMetrics();
        meterBinderSet.add(jvmGcMetrics);
        JvmThreadMetrics jvmThreadMetrics = new JvmThreadMetrics();
        meterBinderSet.add(jvmThreadMetrics);
        JvmMemoryMetrics jvmMemoryMetrics = new JvmMemoryMetrics();
        meterBinderSet.add(jvmMemoryMetrics);
        ClassLoaderMetrics classLoaderMetrics = new ClassLoaderMetrics();
        meterBinderSet.add(classLoaderMetrics);
//        DiskSpaceMetrics diskSpaceMetrics = new DiskSpaceMetrics();
//        ExecutorServiceMetrics executorServiceMetrics = new ExecutorServiceMetrics();
        // 缓存指标
//        CacheMeterBinder cacheMeterBinder = new CacheMeterBinder();
//        CaffeineCacheMetrics caffeineCacheMetrics = new CaffeineCacheMetrics();
//        GuavaCacheMetrics guavaCacheMetrics = new GuavaCacheMetrics();
//        HazelcastCacheMetrics hazelcastCacheMetrics = new HazelcastCacheMetrics();
//        JCacheMetrics jCacheMetrics = new JCacheMetrics();
        // DB指标
//        DatabaseTableMetrics databaseTableMetrics = new DatabaseTableMetrics();
//        PostgreSQLDatabaseMetrics postgreSQLDatabaseMetrics = new PostgreSQLDatabaseMetrics();
        // 系统指标
        FileDescriptorMetrics fileDescriptorMetrics = new FileDescriptorMetrics();
        meterBinderSet.add(fileDescriptorMetrics);
        ProcessorMetrics processorMetrics = new ProcessorMetrics();
        meterBinderSet.add(processorMetrics);
        UptimeMetrics uptimeMetrics = new UptimeMetrics();
        meterBinderSet.add(uptimeMetrics);
        // logging指标
        Log4j2Metrics log4j2Metrics = new Log4j2Metrics();
        meterBinderSet.add(log4j2Metrics);
        LogbackMetrics logbackMetrics = new LogbackMetrics();
       // jetty指标
        JettyServerThreadPoolMetrics jettyServerThreadPoolMetrics = new JettyServerThreadPoolMetrics();
        JettyStatisticsMetrics jettyStatisticsMetrics = new JettyStatisticsMetrics();
        // tomcat指标
        Manager standardManager = new StandardManager();
        TomcatMetrics tomcatMetrics = new TomcatMetrics(standardManager, Collections.EMPTY_LIST);
        meterBinderSet.add(tomcatMetrics);
        // kafka指标
        KafkaConsumerMetrics kafkaConsumerMetrics = new KafkaConsumerMetrics();
        //jpa指标
        HibernateMetrics hibernateMetrics = new HibernateMetrics();
        hystrix指标
        HystrixMetrics hystrixMetrics = new HystrixMetrics();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        try {
            String response = registry.scrape();
            writer.write(response);
            writer.flush();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            writer.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值